How to close Picture in Picture programmatically

Viewed 3214

I have this problem with Picture in Picture mode that i want to close the PIP (Picture in Picture) when the activity is opened again from somewhere other than the PIP itself. Not from the close button.

I want the same scenario that youtube has i.e. when user clicks the PIP (Picture in Picture) it opens the same activity but when user selects another video form the list it ends the previous PIP (Picture in Picture) and opens a new activity. In my case when i open a new video it resumes the video i was previously playing.

3 Answers

There are two possible ways to do this:

  1. If you have activity access then move the activity to the back.

    activity.moveTaskToBack(false);
    

From Official Documentation

Move the task containing this activity to the back of the activity stack. The activity's order within the task is unchanged.

  1. You can restore the activity to the front

    Intent intent = new Intent(PipScreenActivity.this, PipScreenActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    activity.startActivity(intent);
    

Activity A

 Intent intent = new Intent("finish_activity");
            sendBroadcast(intent);

Activity B

 BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent intent) {
            String action = intent.getAction();
            if (action.equals("finish_activity")) {
                finish();
            }
        }
    };
    registerReceiver(broadcastReceiver, new IntentFilter("finish_activity"));
@Override
public void onResume() {
    super.onResume();
    if(!AppPreferences.getIsSameCinema(this).equals(idtitle)){//check is this a new film or no
        idtitle = AppPreferences.getIsSameCinema(this);
        streamLink = AppPreferences.getLinkCinema(this);
        stopPlayer();
        startPlayer(); //full player start
    } else{
        resumePlayer(); //prepare and setPlayWhenReady(true);
    }
}

idtitle and streamLink - extras for current player intent

idtitle - UUID, streamLink - video url

Change SharedPreferences when player activity starts.

Related