Skip to content

Instantly share code, notes, and snippets.

@laithnurie
Created February 21, 2018 10:33
Show Gist options
  • Save laithnurie/072b9b9bbbc30cb815f740124c157005 to your computer and use it in GitHub Desktop.
Save laithnurie/072b9b9bbbc30cb815f740124c157005 to your computer and use it in GitHub Desktop.
Picture in Picture PIP Android
@Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
if (isInPictureInPictureMode) {
updatePictureInPictureState(true);
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || ACTION_MEDIA_CONTROL != intent.getAction()) {
return;
}
int controlType = intent.getIntExtra(EXTRA_CONTROL_TYPE, 0);
if (controlType == CONTROL_TYPE_PLAY) {
playerView.play();
updatePictureInPictureActions(R.drawable.player_pause_button_24dp,
"Pause", CONTROL_TYPE_PAUSE, REQUEST_PAUSE);
} else {
playerView.pause();
updatePictureInPictureActions(R.drawable.player_play_button_24dp,
"Play", CONTROL_TYPE_PLAY, REQUEST_PLAY);
}
}
};
registerReceiver(broadcastReceiver, new IntentFilter(ACTION_MEDIA_CONTROL));
} else {
unregisterReceiver(broadcastReceiver);
broadcastReceiver = null;
}
}
private void updatePictureInPictureState(boolean isPlaying) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (isPlaying) {
updatePictureInPictureActions(R.drawable.player_pause_button_24dp,
"Pause", CONTROL_TYPE_PAUSE, REQUEST_PAUSE);
} else {
updatePictureInPictureActions(R.drawable.player_play_button_24dp,
"Play", CONTROL_TYPE_PLAY, REQUEST_PLAY);
}
}
}
@SuppressLint("NewApi")
private void updatePictureInPictureActions(int iconId, String title, int controlType, int requestCode) {
List<RemoteAction> actions = new ArrayList<>();
PendingIntent intent = PendingIntent.getBroadcast(this,
requestCode, new Intent(ACTION_MEDIA_CONTROL).putExtra(EXTRA_CONTROL_TYPE, controlType), 0);
Icon icon = Icon.createWithResource(this, iconId);
actions.add(new RemoteAction(icon, title, title, intent));
PictureInPictureParams.Builder pictureInPictureParamsBuilder = new PictureInPictureParams.Builder();
pictureInPictureParamsBuilder.setActions(actions).build();
setPictureInPictureParams(pictureInPictureParamsBuilder.build());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment