androidexoplayerpicture-in-pictureandroid-picture-in-picture

Is there a way to restrict Picture-in-picture to only work within an application and not persist when backgrounded?


Is there any way to allow PiP functionality only while the user is within an application?

Ideally, the user can launch PiP, but when they background the app the PiP would dismiss and background playback would continue.


Solution

  • The way to achieve this is by using the onUserLeaveHint() callback from the Framework.

    The example given by the documentation is the opposite of what you're trying to do, but just flip the boolean. ;)

    You might want to include logic that switches an activty into PIP mode instead of going into the background. For example, Google Maps switches to PIP mode if the user presses the home or recents button while the app is navigating. You can catch this case by overriding onUserLeaveHint():

    source: https://developer.android.com/guide/topics/ui/picture-in-picture

    @Override
    public void onUserLeaveHint () {
        if (iWantToBeInPipModeNow()) {
            enterPictureInPictureMode();
        }
    }
    

    What the method iWantToBeInPipModeNow() does is really up-2-you, but you could intercept that, and exit PiP (if you are in it).

    You can also ensure your back/stop methods also ensure PiP is handled appropriately for your use case.