result = audioManager.requestAudioFocus( mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // Proceed with the playing of glorious music } // On stop audioManager.abandonAudioFocus(mOnAudioFocusChangeListener); Audio Focus Ensure apps don’t talk over one another Hold audio focus until we’ve stopped playback
onReceive(Context context, Intent intent) { // Pause the music } }; // On Play IntentFilter filter = new IntentFilter( AudioManager.ACTION_AUDIO_BECOMING_NOISY)); registerReceiver(mNoisyReceiver, filter); // On Pause unregisterReceiver(mNoisyReceiver); ACTION_AUDIO_BECOMING_NOISY
MediaSessionCompat.Callback instance serves as a single point in your app where all media control callbacks flow into. Can be swapped at runtime to change behavior (Local vs Remote for instance)
mMediaSession.setFlags( MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS); // Right after audio focus mMediaSession.setActive(true); // On stop mMediaSession.setActive(false); // On destroy mMediaSession.release(); MediaSessionCompat
system sent media buttons, required (technically a PendingIntent API 18+, but there be dragons) Lollipop+: allows restarting playback after the session is stopped (i.e., setActive(false)), optional
to your Service - Has media browser service intent-filter - Has the MEDIA_BUTTON action intent-filter // Translate a MEDIA_BUTTON Intent into Callbacks // Call in onStartCommand(), etc MediaButtonReceiver.handleIntent(mMediaSession, intent);
pause stop release Audio Focus request focus abandon focus BECOMING_ NOISY register unregister MediaSession Compat new set flags set callback setActive(true) set metadata set state set state setActive(false) release Notification show notification update notification clear notification Minimum Viable Product
= new MediaControllerCompat(this, // Context token); // Part of FragmentActivity setSupportMediaController(mediaController); mButton.setOnClickListener(view -> getSupportMediaController().getTransportControls().pause() ); Getting started
{ // This should probably do something useful if (TextUtils.equals(clientPackageName, getPackageName()) { return new BrowserRoot(getString(R.string.app_name), null); } return null; } @Override public void onLoadChildren(String parentId, Result<List<MediaBrowerCompat.MediaItem>> result) { result.sendResult(null); }
= mediaBrowser.getSessionToken(); // Set us up the MediaControllerCompat } @Override public void onConnectionSuspended() {} @Override public void onConnectionFailed() {} } ConnectionCallbacks
pause stop release Audio Focus request focus abandon focus BECOMING_ NOISY register unregister MediaSession Compat new set flags set callback setActive(true) set metadata set state set state setActive(false) release Notification start FG stopFG(false) stopFG(true) Service set token startService stopSelf Lifecycle of media playback