MediaSessionService


public abstract class MediaSessionService extends Service

Known direct subclasses
MediaLibraryService

Superclass to be extended by services hosting media library sessions.


Superclass to be extended by services hosting media sessions.

It's highly recommended for an app to use this class if media playback should continue while in the background. The service allows other apps to know that your app supports even when your app isn't running. This way, a user voice command may be able start your app to play media.

To extend this class, declare the intent filter in your AndroidManifest.xml:

<service
  android:name="NameOfYourService"
  android:foregroundServiceType="mediaPlayback"
  android:exported="true">
  <intent-filter>
    <action android:name="androidx.media3.session.MediaSessionService"/>
  </intent-filter>
</service>

You may also declare the action android.media.browse.MediaBrowserService for compatibility with android.support.v4.media.MediaBrowserCompat. This service can handle the case automatically.

It's recommended for an app to have a single service declared in the manifest. Otherwise, your app might be shown twice in the list of the controller apps, or another app might fail to pick the right service when it wants to start a playback on this app. If you want to provide multiple sessions, take a look at Supporting Multiple Sessions.

Topics covered here:

  1. Service Lifecycle
  2. Supporting Multiple Sessions

Service Lifecycle

A media session service is a bound service and its foreground service type must include mediaPlayback. When a MediaController is created for the service, the controller binds to the service. onGetSession will be called from onBind.

After binding, the session's onConnect will be called to accept or reject the connection request from the controller. If it's accepted, the controller will be available and keep the binding. If it's rejected, the controller will unbind.

onUpdateNotification will be called whenever a notification needs to be shown, updated or cancelled. The default implementation will display notifications using a default UI or using a MediaNotification.Provider that's set with setMediaNotificationProvider. In addition, when playback starts, the service will become a foreground service. It's required to keep the playback after the controller is destroyed. The service will become a background service when all playbacks are stopped. Apps targeting SDK_INT >= 28 must request the permission, FOREGROUND_SERVICE, in order to make the service foreground. You can control when to show or hide notifications by overriding onUpdateNotification. In this case, you must also start or stop the service from the foreground, when playback starts or stops respectively.

The service will be destroyed when all sessions are released, or no controller is binding to the service while the service is in the background.

Supporting Multiple Sessions

Generally, multiple sessions aren't necessary for most media apps. One exception is if your app can play multiple media contents at the same time, but only for playback of video-only media or remote playback, since the audio focus policy recommends not playing multiple audio contents at the same time. Also, keep in mind that multiple media sessions would make Android Auto and Bluetooth devices with a display to show your apps multiple times, because they list up media sessions, not media apps.

However, if you're capable of handling multiple playbacks and want to keep their sessions while the app is in the background, create multiple sessions and add them to this service with addSession.

Note that a MediaController can be created with SessionToken to connect to a session in this service. In that case, onGetSession will be called to decide which session to handle the connection request. Pick the best session among the added sessions, or create a new session and return it from onGetSession.

Summary

Nested types

Listener for MediaSessionService.

Constants

static final String
SERVICE_INTERFACE = "androidx.media3.session.MediaSessionService"

The action for Intent filter that must be declared by the service.

Public constructors

Creates a service.

Public methods

final void

Adds a MediaSession to this service.

final void

Clears the listener.

final List<MediaSession>

Returns the list of sessions that you've added to this service via addSession or onGetSession.

boolean

Returns whether there is a session with ongoing playback that must be paused or stopped before being able to terminate the service by calling stopSelf.

final boolean

Returns whether session has been added to this service via addSession or onGetSession.

@Nullable IBinder

Called when a component is about to bind to the service.

void

Called when the service is created.

void

Called when the service is no longer used and is being removed.

abstract @Nullable MediaSession

Called when a MediaController is created with this service's SessionToken.

int
@CallSuper
onStartCommand(@Nullable Intent intent, int flags, int startId)

Called when a component calls startService.

void

If playback is ongoing, the service continues running in the foreground when the app is dismissed from the recent apps.

void

This method is deprecated.

Use onUpdateNotification instead.

void
onUpdateNotification(
    MediaSession session,
    boolean startInForegroundRequired
)

Called when a notification needs to be updated.

void

Pauses the player of each session managed by the service and calls stopSelf.

final void

Removes a MediaSession from this service.

final void

Sets the listener.

Protected methods

final void

Sets the MediaNotification.Provider to customize notifications.

Inherited Constants

From android.content.ComponentCallbacks2
static final int
static final int
static final int
static final int
static final int
static final int
static final int
From android.content.Context
static final String
ACCESSIBILITY_SERVICE = "accessibility"
static final String
ACCOUNT_SERVICE = "account"
static final String
ACTIVITY_SERVICE = "activity"
static final String
ALARM_SERVICE = "alarm"
static final String
APPWIDGET_SERVICE = "appwidget"
static final String
APP_OPS_SERVICE = "appops"
static final String
APP_SEARCH_SERVICE = "app_search"
static final String
AUDIO_SERVICE = "audio"
static final String
BATTERY_SERVICE = "batterymanager"
static final int
static final int
static final int
static final int
static final int
static final int
static final int
BIND_EXTERNAL_SERVICE = -2147483648
static final long
BIND_EXTERNAL_SERVICE_LONG = 4611686018427387904
static final int
static final int
static final int
static final int
static final int
static final int
static final String
BIOMETRIC_SERVICE = "biometric"
static final String
BLOB_STORE_SERVICE = "blob_store"
static final String
BLUETOOTH_SERVICE = "bluetooth"
static final String
BUGREPORT_SERVICE = "bugreport"
static final String
CAMERA_SERVICE = "camera"
static final String
CAPTIONING_SERVICE = "captioning"
static final String
CARRIER_CONFIG_SERVICE = "carrier_config"
static final String
CLIPBOARD_SERVICE = "clipboard"
static final String
COMPANION_DEVICE_SERVICE = "companiondevice"
static final String
CONNECTIVITY_DIAGNOSTICS_SERVICE = "connectivity_diagnostics"
static final String
CONNECTIVITY_SERVICE = "connectivity"
static final String
CONSUMER_IR_SERVICE = "consumer_ir"
static final int
static final int
static final int
static final String
CREDENTIAL_SERVICE = "credential"
static final String
CROSS_PROFILE_APPS_SERVICE = "crossprofileapps"
static final int
static final int
static final String
DEVICE_LOCK_SERVICE = "device_lock"
static final String
DEVICE_POLICY_SERVICE = "device_policy"
static final String
DISPLAY_HASH_SERVICE = "display_hash"
static final String
DISPLAY_SERVICE = "display"
static final String
DOMAIN_VERIFICATION_SERVICE = "domain_verification"
static final String
DOWNLOAD_SERVICE = "download"
static final String
DROPBOX_SERVICE = "dropbox"
static final String
EUICC_SERVICE = "euicc"
static final String
FILE_INTEGRITY_SERVICE = "file_integrity"
static final String
FINGERPRINT_SERVICE = "fingerprint"
static final String
GAME_SERVICE = "game"
static final String
GRAMMATICAL_INFLECTION_SERVICE = "grammatical_inflection"
static final String
HARDWARE_PROPERTIES_SERVICE = "hardware_properties"
static final String
HEALTHCONNECT_SERVICE = "healthconnect"
static final String
INPUT_METHOD_SERVICE = "input_method"
static final String
INPUT_SERVICE = "input"
static final String
IPSEC_SERVICE = "ipsec"
static final String
JOB_SCHEDULER_SERVICE = "jobscheduler"
static final String
KEYGUARD_SERVICE = "keyguard"
static final String
LAUNCHER_APPS_SERVICE = "launcherapps"
static final String
LAYOUT_INFLATER_SERVICE = "layout_inflater"
static final String
LOCALE_SERVICE = "locale"
static final String
LOCATION_SERVICE = "location"
static final String
MEDIA_COMMUNICATION_SERVICE = "media_communication"
static final String
MEDIA_METRICS_SERVICE = "media_metrics"
static final String
MEDIA_PROJECTION_SERVICE = "media_projection"
static final String
MEDIA_ROUTER_SERVICE = "media_router"
static final String
MEDIA_SESSION_SERVICE = "media_session"
static final String
MIDI_SERVICE = "midi"
static final int
MODE_APPEND = 32768
static final int
static final int

This field is deprecated.

static final int
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final String
static final String
NFC_SERVICE = "nfc"
static final String
NOTIFICATION_SERVICE = "notification"
static final String
NSD_SERVICE = "servicediscovery"
static final String
OVERLAY_SERVICE = "overlay"
static final String
PEOPLE_SERVICE = "people"
static final String
PERFORMANCE_HINT_SERVICE = "performance_hint"
static final String
POWER_SERVICE = "power"
static final String
PRINT_SERVICE = "print"
static final int
static final int
static final int
static final String
RESTRICTIONS_SERVICE = "restrictions"
static final String
ROLE_SERVICE = "role"
static final String
SEARCH_SERVICE = "search"
static final String
SENSOR_SERVICE = "sensor"
static final String
SHORTCUT_SERVICE = "shortcut"
static final String
STATUS_BAR_SERVICE = "statusbar"
static final String
STORAGE_SERVICE = "storage"
static final String
STORAGE_STATS_SERVICE = "storagestats"
static final String
SYSTEM_HEALTH_SERVICE = "systemhealth"
static final String
TELECOM_SERVICE = "telecom"
static final String
TELEPHONY_IMS_SERVICE = "telephony_ims"
static final String
static final String
TELEPHONY_SUBSCRIPTION_SERVICE = "telephony_subscription_service"
static final String
TEXT_CLASSIFICATION_SERVICE = "textclassification"
static final String
static final String
TV_INPUT_SERVICE = "tv_input"
static final String
TV_INTERACTIVE_APP_SERVICE = "tv_interactive_app"
static final String
UI_MODE_SERVICE = "uimode"
static final String
USAGE_STATS_SERVICE = "usagestats"
static final String
USB_SERVICE = "usb"
static final String
USER_SERVICE = "user"
static final String
VIBRATOR_MANAGER_SERVICE = "vibrator_manager"
static final String
VIBRATOR_SERVICE = "vibrator"

This field is deprecated.

static final String
VIRTUAL_DEVICE_SERVICE = "virtualdevice"
static final String
VPN_MANAGEMENT_SERVICE = "vpn_management"
static final String
WALLPAPER_SERVICE = "wallpaper"
static final String
WIFI_AWARE_SERVICE = "wifiaware"
static final String
WIFI_P2P_SERVICE = "wifip2p"
static final String
static final String
WIFI_SERVICE = "wifi"
static final String
WINDOW_SERVICE = "window"
From android.app.Service
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int

This field is deprecated.

static final int

Inherited methods

From android.content.Context
final int
getColor(int id)
final ColorStateList
final Drawable
getDrawable(int id)
final String
getString(int resId)
final T
<T> getSystemService(Class<T> serviceClass)
final CharSequence
getText(int resId)
final TypedArray
void
void
sendBroadcastWithMultiplePermissions(
    Intent intent,
    String[] receiverPermissions
)
From android.content.ContextWrapper
boolean
bindIsolatedService(
    Intent service,
    int flags,
    String instanceName,
    Executor executor,
    ServiceConnection conn
)
boolean
bindService(Intent service, ServiceConnection conn, int flags)
boolean
bindServiceAsUser(
    Intent service,
    ServiceConnection conn,
    int flags,
    UserHandle user
)
int
int
checkCallingOrSelfUriPermission(Uri uri, int modeFlags)
int[]
checkCallingOrSelfUriPermissions(List<Uri> uris, int modeFlags)
int
int
checkCallingUriPermission(Uri uri, int modeFlags)
int[]
checkCallingUriPermissions(List<Uri> uris, int modeFlags)
int
checkPermission(String permission, int pid, int uid)
int
int
checkUriPermission(Uri uri, int pid, int uid, int modeFlags)
int[]
checkUriPermissions(List<Uri> uris, int pid, int uid, int modeFlags)
void

This method is deprecated.

Context
Context
Context
Context
Context
createDeviceContext(int deviceId)
Context
Context
Context
createPackageContext(String packageName, int flags)
Context
createWindowContext(int type, Bundle options)
String[]
boolean
boolean
boolean
void
void
enforceCallingOrSelfUriPermission(
    Uri uri,
    int modeFlags,
    String message
)
void
enforceCallingPermission(String permission, String message)
void
enforceCallingUriPermission(Uri uri, int modeFlags, String message)
void
enforcePermission(String permission, int pid, int uid, String message)
void
enforceUriPermission(
    Uri uri,
    int pid,
    int uid,
    int modeFlags,
    String message
)
String[]
Context
ApplicationInfo
AssetManager
AttributionSource
String
Context
File
ClassLoader
File
ContentResolver
File
File
int
File
getDir(String name, int mode)
Display
File
File[]
File
File[]
File[]

This method is deprecated.

File
File
Executor
Looper
File
File
File[]
String
String
PackageManager
String
String
ContextParams
Resources
SharedPreferences
getSharedPreferences(String name, int mode)
Object
String
Resources.Theme
Drawable

This method is deprecated.

int

This method is deprecated.

int

This method is deprecated.

void
grantUriPermission(String toPackage, Uri uri, int modeFlags)
boolean
boolean
boolean
boolean
moveDatabaseFrom(Context sourceContext, String name)
boolean
moveSharedPreferencesFrom(Context sourceContext, String name)
FileInputStream
FileOutputStream
openFileOutput(String name, int mode)
SQLiteDatabase
openOrCreateDatabase(
    String name,
    int mode,
    SQLiteDatabase.CursorFactory factory
)
Drawable

This method is deprecated.

void
void
Intent
void

This method is deprecated.

void

This method is deprecated.

void
void
revokeUriPermission(Uri uri, int modeFlags)
void
void
void
sendOrderedBroadcast(Intent intent, String receiverPermission)
void
sendOrderedBroadcastAsUser(
    Intent intent,
    UserHandle user,
    String receiverPermission,
    BroadcastReceiver resultReceiver,
    Handler scheduler,
    int initialCode,
    String initialData,
    Bundle initialExtras
)
void

This method is deprecated.

void

This method is deprecated.

void
sendStickyOrderedBroadcast(
    Intent intent,
    BroadcastReceiver resultReceiver,
    Handler scheduler,
    int initialCode,
    String initialData,
    Bundle initialExtras
)

This method is deprecated.

void
sendStickyOrderedBroadcastAsUser(
    Intent intent,
    UserHandle user,
    BroadcastReceiver resultReceiver,
    Handler scheduler,
    int initialCode,
    String initialData,
    Bundle initialExtras
)

This method is deprecated.

void
setTheme(int resid)
void

This method is deprecated.

void
startActivities(Intent[] intents)
void
ComponentName
boolean
startInstrumentation(
    ComponentName className,
    String profileFile,
    Bundle arguments
)
void
startIntentSender(
    IntentSender intent,
    Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags
)
ComponentName
boolean
void
void
void
void
void
updateServiceGroup(ServiceConnection conn, int group, int importance)
From android.app.Service
void
void
dump(FileDescriptor fd, PrintWriter writer, String[] args)
final Application
final int
void
void
void
onRebind(Intent intent)
void
onStart(Intent intent, int startId)

This method is deprecated.

void
onTimeout(int startId)
void
onTrimMemory(int level)
boolean
onUnbind(Intent intent)
final void
startForeground(int id, Notification notification)
final void
stopForeground(boolean removeNotification)

This method is deprecated.

final void
final boolean
stopSelfResult(int startId)

Constants

SERVICE_INTERFACE

public static final String SERVICE_INTERFACE = "androidx.media3.session.MediaSessionService"

The action for Intent filter that must be declared by the service.

Public constructors

MediaSessionService

public MediaSessionService()

Creates a service.

Public methods

addSession

public final void addSession(MediaSession session)

Adds a MediaSession to this service. This is not necessary for most media apps. See Supporting Multiple Sessions for details.

The added session will be removed automatically when the session is released.

This method can be called from any thread.

Parameters
MediaSession session

A session to be added.

clearListener

@UnstableApi
public final void clearListener()

Clears the listener.

This method can be called from any thread.

getSessions

public final List<MediaSessiongetSessions()

Returns the list of sessions that you've added to this service via addSession or onGetSession.

This method can be called from any thread.

isPlaybackOngoing

@UnstableApi
public boolean isPlaybackOngoing()

Returns whether there is a session with ongoing playback that must be paused or stopped before being able to terminate the service by calling stopSelf.

isSessionAdded

public final boolean isSessionAdded(MediaSession session)

Returns whether session has been added to this service via addSession or onGetSession.

This method can be called from any thread.

onBind

@CallSuper
public @Nullable IBinder onBind(@Nullable Intent intent)

Called when a component is about to bind to the service.

The default implementation handles the incoming requests from controllers. In this case, the intent will have the action SERVICE_INTERFACE. Override this method if this service also needs to handle actions other than SERVICE_INTERFACE.

This method will be called on the main thread.

onCreate

@CallSuper
public void onCreate()

Called when the service is created.

Override this method if you need your own initialization.

This method will be called on the main thread.

onDestroy

@CallSuper
public void onDestroy()

Called when the service is no longer used and is being removed.

Override this method if you need your own clean up.

This method will be called on the main thread.

onGetSession

public abstract @Nullable MediaSession onGetSession(MediaSession.ControllerInfo controllerInfo)

Called when a MediaController is created with this service's SessionToken. Return a MediaSession that the controller will connect to, or null to reject the connection request.

The service automatically maintains the returned sessions. In other words, a session returned by this method will be added to the service, and removed from the service when the session is closed. You don't need to manually call addSession nor removeSession.

There are two special cases where the getPackageName returns a non-existent package name:

  • When the service is started by a media button event, the package name will be ACTION_MEDIA_BUTTON. If you want to allow the service to be started by media button events, do not return null.
  • When a legacy android.media.browse.MediaBrowser or a android.support.v4.media.MediaBrowserCompat tries to connect, the package name will be SERVICE_INTERFACE. If you want to allow the service to be bound by the legacy media browsers, do not return null.

For those special cases, the values returned by getUid and getConnectionHints have no meaning.

This method will be called on the main thread.

Parameters
MediaSession.ControllerInfo controllerInfo

The information of the controller that is trying to connect.

Returns
@Nullable MediaSession

A MediaSession for the controller, or null to reject the connection.

onStartCommand

@CallSuper
public int onStartCommand(@Nullable Intent intent, int flags, int startId)

Called when a component calls startService.

The default implementation handles the incoming media button events. In this case, the intent will have the action ACTION_MEDIA_BUTTON. Override this method if this service also needs to handle actions other than ACTION_MEDIA_BUTTON.

This method will be called on the main thread.

onTaskRemoved

public void onTaskRemoved(@Nullable Intent rootIntent)

If playback is ongoing, the service continues running in the foreground when the app is dismissed from the recent apps. Otherwise, the service is stopped by calling stopSelf which terminates the service lifecycle and triggers onDestroy that an app can override to release the sessions and other resources.

An app can safely override this method without calling super to implement a different behaviour, for instance unconditionally calling pauseAllPlayersAndStopSelf to stop the service even when playing. However, if playback is not ongoing, the service must be terminated otherwise the service will be crashed and restarted by the system.

Note: The service can't be stopped until all media controllers have been unbound. Hence, an app needs to release all internal controllers that have connected to the service (for instance from an activity in onStop). If an app allows external apps to connect a MediaController to the service, these controllers also need to be disconnected. In such a scenario of external bound clients, an app needs to override this method to release the session before calling stopSelf.

onUpdateNotification

public void onUpdateNotification(MediaSession session)

onUpdateNotification

public void onUpdateNotification(
    MediaSession session,
    boolean startInForegroundRequired
)

Called when a notification needs to be updated. Override this method to show or cancel your own notifications.

This method is called whenever the service has detected a change that requires to show, update or cancel a notification with a flag startInForegroundRequired suggested by the service whether starting in the foreground is required. The method will be called on the application thread of the app that the service belongs to.

Override this method to create your own notification and customize the foreground handling of your service.

The default implementation will present a default notification or the notification provided by the MediaNotification.Provider that is set by the app. Further, the service is started in the foreground when playback is ongoing and put back into background otherwise.

Apps targeting SDK_INT >= 28 must request the permission, FOREGROUND_SERVICE.

This method will be called on the main thread.

Parameters
MediaSession session

A session that needs notification update.

boolean startInForegroundRequired

Whether the service is required to start in the foreground.

pauseAllPlayersAndStopSelf

@UnstableApi
public void pauseAllPlayersAndStopSelf()

Pauses the player of each session managed by the service and calls stopSelf.

This terminates the service lifecycle and triggers onDestroy that an app can override to release the sessions and other resources.

removeSession

public final void removeSession(MediaSession session)

Removes a MediaSession from this service. This is not necessary for most media apps. See Supporting Multiple Sessions for details.

This method can be called from any thread.

Parameters
MediaSession session

A session to be removed.

setListener

@UnstableApi
public final void setListener(MediaSessionService.Listener listener)

Sets the listener.

This method can be called from any thread.

Protected methods

setMediaNotificationProvider

@UnstableApi
protected final void setMediaNotificationProvider(
    MediaNotification.Provider mediaNotificationProvider
)

Sets the MediaNotification.Provider to customize notifications.

This should be called before onCreate returns.

This method can be called from any thread.