privatevalintentFilter=IntentFilter(ACTION_AUDIO_BECOMING_NOISY)// Defined elsewhere...privatelateinitvarafChangeListener:AudioManager.OnAudioFocusChangeListenerprivatevalmyNoisyAudioStreamReceiver=BecomingNoisyReceiver()privatelateinitvarmyPlayerNotification:MediaStyleNotificationprivatelateinitvarmediaSession:MediaSessionCompatprivatelateinitvarservice:MediaBrowserServiceprivatelateinitvarplayer:SomeKindOfPlayerprivatelateinitvaraudioFocusRequest:AudioFocusRequestprivatevalcallback=object:MediaSessionCompat.Callback(){overridefunonPlay(){valam=context.getSystemService(Context.AUDIO_SERVICE)asAudioManager// Request audio focus for playback, this registers the afChangeListeneraudioFocusRequest=AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).run{setOnAudioFocusChangeListener(afChangeListener)setAudioAttributes(AudioAttributes.Builder().run{setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)build()})build()}valresult=am.requestAudioFocus(audioFocusRequest)if(result==AudioManager.AUDIOFOCUS_REQUEST_GRANTED){// Start the servicestartService(Intent(context,MediaBrowserService::class.java))// Set the session active (and update metadata and state)mediaSession.isActive=true// start the player (custom call)player.start()// Register BECOME_NOISY BroadcastReceiverregisterReceiver(myNoisyAudioStreamReceiver,intentFilter)// Put the service in the foreground, post notificationservice.startForeground(id,myPlayerNotification)}}publicoverridefunonStop(){valam=context.getSystemService(Context.AUDIO_SERVICE)asAudioManager// Abandon audio focusam.abandonAudioFocusRequest(audioFocusRequest)unregisterReceiver(myNoisyAudioStreamReceiver)// Stop the serviceservice.stopSelf()// Set the session inactive (and update metadata and state)mediaSession.isActive=false// stop the player (custom call)player.stop()// Take the service out of the foregroundservice.stopForeground(false)}publicoverridefunonPause(){valam=context.getSystemService(Context.AUDIO_SERVICE)asAudioManager// Update metadata and state// pause the player (custom call)player.pause()// unregister BECOME_NOISY BroadcastReceiverunregisterReceiver(myNoisyAudioStreamReceiver)// Take the service out of the foreground, retain the notificationservice.stopForeground(false)}}
Java
privateIntentFilterintentFilter=newIntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);// Defined elsewhere...privateAudioManager.OnAudioFocusChangeListenerafChangeListener;privateBecomingNoisyReceivermyNoisyAudioStreamReceiver=newBecomingNoisyReceiver();privateMediaStyleNotificationmyPlayerNotification;privateMediaSessionCompatmediaSession;privateMediaBrowserServiceservice;privateSomeKindOfPlayerplayer;privateAudioFocusRequestaudioFocusRequest;MediaSessionCompat.Callbackcallback=newMediaSessionCompat.Callback(){@OverridepublicvoidonPlay(){AudioManageram=(AudioManager)context.getSystemService(Context.AUDIO_SERVICE);// Request audio focus for playback, this registers the afChangeListenerAudioAttributesattrs=newAudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();audioFocusRequest=newAudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).setOnAudioFocusChangeListener(afChangeListener).setAudioAttributes(attrs).build();intresult=am.requestAudioFocus(audioFocusRequest);if(result==AudioManager.AUDIOFOCUS_REQUEST_GRANTED){// Start the servicestartService(newIntent(context,MediaBrowserService.class));// Set the session active (and update metadata and state)mediaSession.setActive(true);// start the player (custom call)player.start();// Register BECOME_NOISY BroadcastReceiverregisterReceiver(myNoisyAudioStreamReceiver,intentFilter);// Put the service in the foreground, post notificationservice.startForeground(id,myPlayerNotification);}}@OverridepublicvoidonStop(){AudioManageram=(AudioManager)context.getSystemService(Context.AUDIO_SERVICE);// Abandon audio focusam.abandonAudioFocusRequest(audioFocusRequest);unregisterReceiver(myNoisyAudioStreamReceiver);// Stop the serviceservice.stopSelf();// Set the session inactive (and update metadata and state)mediaSession.setActive(false);// stop the player (custom call)player.stop();// Take the service out of the foregroundservice.stopForeground(false);}@OverridepublicvoidonPause(){AudioManageram=(AudioManager)context.getSystemService(Context.AUDIO_SERVICE);// Update metadata and state// pause the player (custom call)player.pause();// unregister BECOME_NOISY BroadcastReceiverunregisterReceiver(myNoisyAudioStreamReceiver);// Take the service out of the foreground, retain the notificationservice.stopForeground(false);}};
[null,null,["最后更新时间 (UTC):2025-07-27。"],[],[],null,["# Media session callbacks\n\nYour media session callbacks call methods in several APIs to control the player, manage the audio focus,\nand communicate with the media session and media browser service. Note that the\n`MediaSession` logic that responds to callbacks must be consistent. The behavior\nof the callback must not depend on the identity of the caller, which could be\nan activity in the same app running the `MediaSession` or any other app with a\n`MediaController` connected to the `MediaSession`.\n\nThe following table summarizes how these tasks are distributed across callbacks.\n\n\u003cbr /\u003e\n\n|-------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------|------------------------------------------------|\n| | **onPlay()** | **onPause()** | **onStop()** |\n| [Audio Focus](/guide/topics/media-apps/audio-focus) | `requestFocus()` passing in your `OnAudioFocusChangeListener`. *Always call `requestFocus()` first, proceed only if focus is granted.* | | `abandonAudioFocus()` |\n| [Service](/guide/topics/media-apps/audio-app/building-a-mediabrowserservice) | `startService()` | | `stopSelf()` |\n| [Media Session](/guide/topics/media-apps/working-with-a-media-session) | `setActive(true)` - Update metadata and state | - Update metadata and state | `setActive(false)` - Update metadata and state |\n| Player Implementation | Start the player | Pause the player | Stop the player |\n| [Becoming Noisy](/guide/topics/media-apps/volume-and-earphones#becoming-noisy) | Register your `BroadcastReceiver` | Unregister your `BroadcastReceiver` | |\n| [Notifications](/guide/topics/media-apps/audio-app/building-a-mediabrowserservice#mediastyle-notifications) | `startForeground(notification)` | `stopForeground(false)` | `stopForeground(false)` |\n\n\u003cbr /\u003e\n\nHere is a sample framework for the callback: \n\n### Kotlin\n\n```kotlin\nprivate val intentFilter = IntentFilter(ACTION_AUDIO_BECOMING_NOISY)\n\n// Defined elsewhere...\nprivate lateinit var afChangeListener: AudioManager.OnAudioFocusChangeListener\nprivate val myNoisyAudioStreamReceiver = BecomingNoisyReceiver()\nprivate lateinit var myPlayerNotification: MediaStyleNotification\nprivate lateinit var mediaSession: MediaSessionCompat\nprivate lateinit var service: MediaBrowserService\nprivate lateinit var player: SomeKindOfPlayer\n\nprivate lateinit var audioFocusRequest: AudioFocusRequest\n\nprivate val callback = object: MediaSessionCompat.Callback() {\n override fun onPlay() {\n val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager\n // Request audio focus for playback, this registers the afChangeListener\n\n audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).run {\n setOnAudioFocusChangeListener(afChangeListener)\n setAudioAttributes(AudioAttributes.Builder().run {\n setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)\n build()\n })\n build()\n }\n val result = am.requestAudioFocus(audioFocusRequest)\n if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {\n // Start the service\n startService(Intent(context, MediaBrowserService::class.java))\n // Set the session active (and update metadata and state)\n mediaSession.isActive = true\n // start the player (custom call)\n player.start()\n // Register BECOME_NOISY BroadcastReceiver\n registerReceiver(myNoisyAudioStreamReceiver, intentFilter)\n // Put the service in the foreground, post notification\n service.startForeground(id, myPlayerNotification)\n }\n }\n\n public override fun onStop() {\n val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager\n // Abandon audio focus\n am.abandonAudioFocusRequest(audioFocusRequest)\n unregisterReceiver(myNoisyAudioStreamReceiver)\n // Stop the service\n service.stopSelf()\n // Set the session inactive (and update metadata and state)\n mediaSession.isActive = false\n // stop the player (custom call)\n player.stop()\n // Take the service out of the foreground\n service.stopForeground(false)\n }\n\n public override fun onPause() {\n val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager\n // Update metadata and state\n // pause the player (custom call)\n player.pause()\n // unregister BECOME_NOISY BroadcastReceiver\n unregisterReceiver(myNoisyAudioStreamReceiver)\n // Take the service out of the foreground, retain the notification\n service.stopForeground(false)\n }\n}\n```\n\n### Java\n\n```java\nprivate IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);\n\n// Defined elsewhere...\nprivate AudioManager.OnAudioFocusChangeListener afChangeListener;\nprivate BecomingNoisyReceiver myNoisyAudioStreamReceiver = new BecomingNoisyReceiver();\nprivate MediaStyleNotification myPlayerNotification;\nprivate MediaSessionCompat mediaSession;\nprivate MediaBrowserService service;\nprivate SomeKindOfPlayer player;\n\nprivate AudioFocusRequest audioFocusRequest;\n\nMediaSessionCompat.Callback callback = new\n MediaSessionCompat.Callback() {\n @Override\n public void onPlay() {\n AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n // Request audio focus for playback, this registers the afChangeListener\n AudioAttributes attrs = new AudioAttributes.Builder()\n .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)\n .build();\n audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)\n .setOnAudioFocusChangeListener(afChangeListener)\n .setAudioAttributes(attrs)\n .build();\n int result = am.requestAudioFocus(audioFocusRequest);\n\n if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {\n // Start the service\n startService(new Intent(context, MediaBrowserService.class));\n // Set the session active (and update metadata and state)\n mediaSession.setActive(true);\n // start the player (custom call)\n player.start();\n // Register BECOME_NOISY BroadcastReceiver\n registerReceiver(myNoisyAudioStreamReceiver, intentFilter);\n // Put the service in the foreground, post notification\n service.startForeground(id, myPlayerNotification);\n }\n }\n\n @Override\n public void onStop() {\n AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n // Abandon audio focus\n am.abandonAudioFocusRequest(audioFocusRequest);\n unregisterReceiver(myNoisyAudioStreamReceiver);\n // Stop the service\n service.stopSelf();\n // Set the session inactive (and update metadata and state)\n mediaSession.setActive(false);\n // stop the player (custom call)\n player.stop();\n // Take the service out of the foreground\n service.stopForeground(false);\n }\n\n @Override\n public void onPause() {\n AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n // Update metadata and state\n // pause the player (custom call)\n player.pause();\n // unregister BECOME_NOISY BroadcastReceiver\n unregisterReceiver(myNoisyAudioStreamReceiver);\n // Take the service out of the foreground, retain the notification\n service.stopForeground(false);\n }\n };\n```\n| **Note:** People using the Google Assistant can control your app with voice commands if you create your MediaSession with the necessary callbacks. The requirements are explained in the [Google Assistant documentation](/guide/topics/media-apps/interacting-with-assistant)."]]