Enable Background Audio

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.

📘

LIFECYCLE EXPLAINED

  1. From the Activity, get a reference to the JWPlayer.
  2. From the Activity, instantiate MediaServiceController.
  3. Once playback begins, call the bindService() on the MediaServiceController to show the Media notification.
  4. From the Activity's onDestroy(), call unbindService() on the MediaServiceController to teardown the Service and Notification. It is important to call unbindService() to prevent any memory leaks.


Implementation

  1. In the AndroidManifest.xml, add the MediaService and MediaButtonReceiver.
<?xml version="1.0" encoding="utf-8"?>
<manifest
    ...>
    <application
        ...>
        
        ...
        <receiver android:name="androidx.media.session.MediaButtonReceiver">
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </receiver>
        <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>
  1. Use MediaServiceController.Builder() to create an instance of MediaServiceController. Provide the method the Activity and the JWPlayer that the service should control.
    The MediaServiceController class offers a convenient API to bind and unbind the MediaService as well as to update the ServiceMediaApi with a new player.
mMediaServiceController = new MediaServiceController.Builder(mActivity,mJWPlayer).build();
  1. Call bindService() to show the Media notification or unbindService() 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.

ClassDescription
NotificationHelperResponsible 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 JW Player or try extending it to add or override the functionality you want.
ServiceMediaApiClass 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.


Did this page help you?