Enable Background Audio (Android)
Allow your viewers to listen to audio when the app is no longer in the foreground
If you have a media application that plays video podcasts, enabling Background Audio allows your viewers to play the podcast audio while they are no longer actively using your app or have locked their device.
Lifecycle
The following diagram illustrates a lifecycle for Background Audio.
- From the
Activity
, get a reference to theJWPlayer
.- From the
Activity
, instantiateMediaServiceController
.- Once playback begins, call the
bindService()
on theMediaServiceController
to show the Media notification.- From the
Activity
'sonDestroy()
, callunbindService()
on theMediaServiceController
to teardown the Service and Notification. It is important to callunbindService()
to prevent any memory leaks.
Implementation
-
In the AndroidManifest.xml, add the
MediaService
.<?xml version="1.0" encoding="utf-8"?> <manifest ...> <application ...> ... <service android:name="com.jwplayer.pub.api.background.MediaService" android:exported="false"> <intent-filter> <action android:name="android.intent.action.MEDIA_BUTTON" /> </intent-filter> </service> ... </application> </manifest>
-
Use
MediaServiceController.Builder()
to create an instance ofMediaServiceController
. Provide the method theActivity
and theJWPlayer
that the service should control.The
MediaServiceController
class offers a convenient API to bind and unbind theMediaService
as well as to update theServiceMediaApi
with a new player.mMediaServiceController = new MediaServiceController.Builder(mActivity,mJWPlayer).build();
-
Call
bindService()
to show the Media notification orunbindService()
to teardown the Service and Notification.
Customization
By using the MediaServiceController.Builder()
, you can specify your own implementations of ServiceMediaApi
or NotificationHelper
to provide the type of functionality you want for your media application. Each class is explained below.
Class | Description |
---|---|
NotificationHelper | Responsible for defining the Notification styling and details If you want to customize the behavior of this class, you can either use the Builder() provided by JWP or try extending it to add or override the functionality you want. |
ServiceMediaApi | Class responsible for defining the APIs available to the Notification If you want to customize the behavior of this class, it is recommended that you extend it and add or override the functionality you want. |
Updated 10 months ago