How Do We Leave Picture-In-Picture Mode?

CommonsWare picture CommonsWare · Apr 3, 2017 · Viewed 10.4k times · Source

We have enterPictureInPictureMode() to move an activity from its current form into a picture-in-picture representation.

What is the means by which we revert that, returning the activity to its normal state, besides destroying the activity? There is no exitPictureInPictureMode(), leavePictureInPictureMode(), or janeGetMeOffThisCrazyPictureInPictureModeThing() method on Activity, and the documentation does not seem to cover an alternative.

I am interested in a solution for Android O, for picture-in-picture mode on mobile devices, though if that works for Android TV too, wonderful!

UPDATE 2017-04-08: If what you want is to return to normal mode when the user clicks the X button to exit picture-in-picture mode, you can do something like this:

  @Override
  public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
    super.onPictureInPictureModeChanged(isInPictureInPictureMode);

    if (!isInPictureInPictureMode) {
      getApplication().startActivity(new Intent(this, getClass())
        .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
    }
  }

The key bits are to call startActivity() to start the current activity again with FLAG_ACTIVITY_REORDER_TO_FRONT. With a singleTask activity, you need to call that on some non-Activity context, such as the Application singleton. This does not appear to trigger onStop() or onStart(), but it does trigger onNewIntent() (with whatever Intent you pass to startActivity()).

Answer

rds picture rds · Apr 8, 2017
  1. Move the activity to the back

    activity.moveTaskToBack(false /* nonRoot */);
    
  2. restore the activity to the front

    Intent startIntent = new Intent(PipActivity.this, PipActivity.class);
    startIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    activity.startActivity(startIntent);