[GUIDE] Implement RemoteController in your app

Search This thread

Dr.Alexander_Breen

Senior Member
Jun 17, 2012
439
1,072
Hello, fellow XDA-ers.
Today I want to tell you about new RemoteController class introduced in Android 4.4.

What does this class do?
The RemoteController class is used to control media playback, display and update media metadata and playback status, published by applications using the RemoteControlClient class.

However, the documentation is rather empty. Sure, there are methods etc., but it's not really helpful if you have zero knowledge about this class and you want to implement it right away.

So, here I am to help you.
Sit down and get your IDE and a cup of coffee/tea ready.

WARNING: This guide is oriented at experienced Android developers. So, I'll cover the main points, but don't expect me to go into details of something which is not directly related to RemoteController.

1. Creating a service to control media playback.
To avoid illegal access to metadata and media playback, user have to activate a specific NotificationListenerService in Security settings.
As a developer, you have to implement one.

Requirements for this service:
1. Has to extend NotificationListenerService[/B
2. Has to implement RemoteController.OnClientUpdateListener.


You can look at my implementation on GitHub.

Let's now talk about details.
It's better to leave onNotificationPosted and onNotificationRemoved empty if you don't plan to actually process notifications in your app; otherwise you know what to do.

Now we need to register this service in AndroidManifest.xml.

Add the following to the manifest(replacing <service-package> with actual package where your service lies, and <service-name> with your Service class name):
Code:
<service
android:name="<service-package>.<service-name>"
android:label="@string/service_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
    <intent-filter>
       <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>
Please note: do not override onBind() method, as it will break the functionality of the service.
"service_name" is a name for your service which will be shown in Security->Notification access.

2. Handling client update events.
Now on to implementation of RemoteController.OnClientUpdateListener. .
You may process everything inside this service, or (which I consider a better alternative, as it gives more flexibility, and you can re-use your service for different apps) re-call methods of external callback to process the client update events.

Here, however, we will only talk about the methods and which parameters are passed to them.
The official description is good enough and I recommend reading it before processing further.


Code:
[B]onClientChange(boolean clearing)[/B]
Pretty self-explanatory. "true" will be passed if metadata has to be cleared as there is no valid RemoteControlClient, "false" otherwise.

Code:
[B]onClientMetadataUpdate(RemoteController.MetadataEditor metadataEditor)[/B]
[I]metadataEditor[/I] is a container which has all the available metadata.

How to access it? Very simple.
For text data, you use RemoteController.MetadataEditor#getString(int key, String defaultValue);

"R.string.unknown" is a reference to String resource with name "unknown", which will be used to replace missing metadata.

To get artist name as a String, use:
[B]metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_TITLE, getString(R.string.unknown))[/B]

To get title of the song as a String, use:
[B]metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_ALBUM, getString(R.string.unknown))[/B]

To get the duration of the song as a long, use:
[B]metadataEditor.getLong(MediaMetadataRetriever.METADATA_KEY_DURATION, 1)[/B]
1 is the default duration of the song to be used in case the duration is unknown.

To get the artwork as a Bitmap, use:
[B]metadataEditor.getBitmap(RemoteController.MetadataEditor.BITMAP_KEY_ARTWORK, null)[/B]
"null" is the default value for the artwork. You may use some placeholder image, however.

And here is one pitfall.
Naturally, you would expect artist name to be saved with the key MediaMetadataRetriever.METADATA_KEY_ARTIST.
However, some players, like PowerAmp, save it with key MediaMetadataRetriever.METADATA_KEY_ALBUMARTIS.

So, to avoid unnecessary checks, you may use the following(returns String):
[B]mArtistText.setText(editor.getString(MediaMetadataRetriever.METADATA_KEY_ARTIST, editor.getString(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST, getString(R.string.unknown))));[/B]

What does it do - it tries to get the artist name by the key METADATA_KEY_ARTIST, and if there is no such String with this key, it will fall back to default value, which, in turn, will try to get the artist name by the key METADATA_KEY_ALBUMARTIST, and if it fails again, it falls back to "unknown" String resource.

So, you may fetch the metadata using these methods and then process it as you like.

Code:
[B]onClientPlaybackStateUpdate(int state, long stateChangeTimeMs, long currentPosMs, float speed)[/B]
Called when the state of the player has changed.
Right now this method is not called, probably due to bug.
[I]state[/I] - playstate of player. Read the [URL="http://developer.android.com/reference/android/media/RemoteControlClient.html"]RemoteControllerClient class description[/URL] to get the list of available playstates.
For example, RemoteControlClient.PLAYSTATE_PLAYING means that music is currently playing.

[I]stateChangeTimeMs[/I] - the system time at which the change happened.

[I]currentPosMs[/I] - current playback position in milliseconds.

[I]speed[/I] - a speed at which playback occurs. 1.0f is normal playback, 2.0f is 2x-speeded playback, 0.5f is 0.5x-speeded playback etc.

Code:
[B]onClientPlaybackStateUpdate (int state)
[I]state[/I] - playstate of player. Read the [URL="http://developer.android.com/reference/android/media/RemoteControlClient.html"]RemoteControllerClient class description[/URL] to get the list of available playstates.[/B]

Code:
[B]onClientTransportControlUpdate (int transportControlFlags)[/B]
[I]transportControlFlags[/I] - player capabilities in form of bitmask.
This is one interesting method. It reports the capabilities of current player in form of bitmask.
Let's say, for example, you want to know if current player supports "fast forward" media key.
Here is how to do it:

[B]if(transportControlFlags & RemoteControlClient.FLAG_KEY_MEDIA_FAST_FORWARD != 0) doSomethingIfSupport(); else doSomethingIfDoesNotSupport(); [/B]

All of the flags are listed in [URL="http://developer.android.com/reference/android/media/RemoteControlClient.html"]RemoteControlClient class description.[/URL]

3. Creating RemoteController object.

The preparations are finished.
Now we need to construct RemoteController object.

The constructor of RemoteController takes two arguments. First is Context, and second is RemoteController.OnClientUpdateListener.
You should know how to fetch Context already.

Now let's talk about the second parameter. You have to pass YOUR SERVICE implementing RemoteController.OnClientUpdateListener and extending NotificationListenerService. This is a must, otherwise you won't be able to register your RemoteController to the system.

So, in your service, use something like this:
Code:
public class RemoteControlService extends NotificationListenerService implements RemoteController.OnClientUpdateListener {
           private RemoteController mRemoteController;
           private Context mContext;
           ...
           @Override
           public void onCreate() {
                mContext = getApplicationContext();
                mRemoteController = new RemoteController(mContext, this);
           }
           ...

Now to activate our RemoteController we have to register it using AudioManager.
Please note that AudioManager#registerRemoteController returns "true" in case the registration was successful, and "false" otherwise.
When can it return "false"? I know only two cases:
1. You have not activated your NotificationListenerService in Security -> Notification Access.
2. Your RemoteController.OnClientUpdateListener implementation is not a class extending NotificationListenerService.
Code:
if(!((AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE)).registerRemoteController(mRemoteController)) {
    //handle registration failure
} else {
    mRemoteController.setArtworkConfiguration(BITMAP_WIDTH, BITMAP_HEIGHT);
    setSynchronizationMode(mRemoteController, RemoteController.POSITION_SYNCHRONIZATION_CHECK);
}

Of course, we will have to deactivate RemoteController at some point with this code.
Code:
((AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE)).unregisterRemoteController(mRemoteController);

By default you will NOT receive artwork updates.
To receive artwork, call setArtworkConfiguration (int, int). First argument is width of the artwork, and second is the height of the artwork.
Please note that this method can fail, so check if it returns true or false.
To stop receiving artwork, call clearArtworkConfiguration().

4. Controlling media playback.

We can send media key events to RemoteControlClient.
Also, we can change position of playback for players which support it(currently only Google Play Music supports it).

You can send key events using this helper method:
Code:
private boolean sendKeyEvent(int keyCode) {
                //send "down" and "up" keyevents.
                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
                boolean first = mRemoteController.sendMediaKeyEvent(keyEvent);
                keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
                boolean second = mRemoteController.sendMediaKeyEvent(keyEvent);
                
                return first && second; //if both  clicks were delivered successfully
}

"keyCode" is the code of the pressed media button. For example, sending KeyEvent.KEYCODE_MEDIA_NEXT will cause the player to change track to next. Note that we send both "down" event and "up" method - without that it will get stuck after first command.

To seek to some position in current song, use RemoteController#seekTo(long). The parameter is the position in the song in milliseconds.
Please note that it will have no effect if the player does not support remote position control.

5. Getting current position.
RIght now the onClientPlaybackStateUpdate(int state, long stateChangeTimeMs, long currentPosMs, float speed) method is broken, as it's not called when the position is updated. So, you have to manually fetch current position. To do this, use the RemoteController#getEstimatedMediaPosition() method - it returns current position in milliseconds(or other values, like 0, if player does not support position update).

To update it periodically, you may use Handler and Runnable. Look at the implementation on GitHub as the reference.
 
Last edited:

doomedez

Member
Sep 26, 2013
22
21
28
Minsk
Hi. Good tutorial! How can i use RemoteController without MediaPlayer class? I'm using custom engine for playback.
 

Timmmmmm

Senior Member
Nov 25, 2009
55
30
XDA is usually pretty shi tty so I never come on here, and hence I had to reset my password to say thank you! This was really useful.
 

corrytrevor

Member
Apr 20, 2012
25
11
Ottawa
www.rebootsramblings.ca
Including this code in NotificationListener Service on 4.3

Thank you for taking the time to describe the implementation in such detail. My only problem now is including implements RemoteController.OnClientUpdateListener in my NotificationListener class for an app that supports 4.0+. As soon as this service is started up by a 4.3 device the app crashes (reason is obvious, 4.3 doesn't support remote controller). The only solution I've found is to create 2 seperate notification listener classes, one for 4.3 and one for 4.4 (which has the RemoteController code in it). This also creates 2 entries in Notification Access list in the security settings.

Any ideas on how to make a hybrid service for 4.3/4.4 that implements the necessary RemoteController code?
 

mrmaffen

Senior Member
Feb 28, 2010
73
8
Thank you for taking the time to describe the implementation in such detail. My only problem now is including implements RemoteController.OnClientUpdateListener in my NotificationListener class for an app that supports 4.0+. As soon as this service is started up by a 4.3 device the app crashes (reason is obvious, 4.3 doesn't support remote controller). The only solution I've found is to create 2 seperate notification listener classes, one for 4.3 and one for 4.4 (which has the RemoteController code in it). This also creates 2 entries in Notification Access list in the security settings.

Any ideas on how to make a hybrid service for 4.3/4.4 that implements the necessary RemoteController code?

I have the exact same problem. Been searching for hours now, but I just couldn't come up with a solution for that issue.

Does anybody know how to solve this? Any kind of hint would be highly appreciated!
 

mrmaffen

Senior Member
Feb 28, 2010
73
8
Thank you for taking the time to describe the implementation in such detail. My only problem now is including implements RemoteController.OnClientUpdateListener in my NotificationListener class for an app that supports 4.0+. As soon as this service is started up by a 4.3 device the app crashes (reason is obvious, 4.3 doesn't support remote controller). The only solution I've found is to create 2 seperate notification listener classes, one for 4.3 and one for 4.4 (which has the RemoteController code in it). This also creates 2 entries in Notification Access list in the security settings.

Any ideas on how to make a hybrid service for 4.3/4.4 that implements the necessary RemoteController code?

I found a solution to this problem (or rather WisdomWolf did). http://stackoverflow.com/questions/...motecontroller-onclientupdatelistener-crashes

Problem solved :)
 
Last edited:
  • Like
Reactions: corrytrevor

abell431

Senior Member
Oct 28, 2011
224
225
Finding music to play


Hi Thanks for the fantastic tutorial! Is there away to find a receiver if there is no music playing. I have noticed the line
Code:
I/RemoteController﹕ No-op when sending key click, no receiver right now
is logged. Thanks
 
Last edited:

bin.shao0604

New member
Sep 7, 2014
1
0
ChengDu
Thanks for the great tutorial, very helpful for my current project. RemoteController is also used in KitKat built-in Keyguard KeyguardTransportControlView to replace RDC in older version.
 

Elizabeth_Keen

New member
Jun 16, 2014
3
1
ATI-ERP expeditious Business Solutions

Great article on building Remotecontroller in an Android application.
For More Android Apps visit ati-erp.com
ATI-ERP
 

zen kun

Senior Member
Jan 23, 2010
1,890
395
Berlin
xdaforums.com
i can't bind the service, i debug and seemd android start the service well , however trying bind the service onStart seems does not work :( in 4.4.4 someone has this issue? :( i tried reboot and other options
Nevermind i forgot to put the intent filter on manifest (shame on me)
 
Last edited:

barkside

Member
Oct 16, 2010
46
14
Sorry to drag up an old thread. Does anyone know how to get the package of the client that is currently connected to / updating the RemoteController? I can't find it anywhere...
 

Top Liked Posts

  • There are no posts matching your filters.
  • 17
    Hello, fellow XDA-ers.
    Today I want to tell you about new RemoteController class introduced in Android 4.4.

    What does this class do?
    The RemoteController class is used to control media playback, display and update media metadata and playback status, published by applications using the RemoteControlClient class.

    However, the documentation is rather empty. Sure, there are methods etc., but it's not really helpful if you have zero knowledge about this class and you want to implement it right away.

    So, here I am to help you.
    Sit down and get your IDE and a cup of coffee/tea ready.

    WARNING: This guide is oriented at experienced Android developers. So, I'll cover the main points, but don't expect me to go into details of something which is not directly related to RemoteController.

    1. Creating a service to control media playback.
    To avoid illegal access to metadata and media playback, user have to activate a specific NotificationListenerService in Security settings.
    As a developer, you have to implement one.

    Requirements for this service:
    1. Has to extend NotificationListenerService[/B
    2. Has to implement RemoteController.OnClientUpdateListener.


    You can look at my implementation on GitHub.

    Let's now talk about details.
    It's better to leave onNotificationPosted and onNotificationRemoved empty if you don't plan to actually process notifications in your app; otherwise you know what to do.

    Now we need to register this service in AndroidManifest.xml.

    Add the following to the manifest(replacing <service-package> with actual package where your service lies, and <service-name> with your Service class name):
    Code:
    <service
    android:name="<service-package>.<service-name>"
    android:label="@string/service_name"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
        <intent-filter>
           <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
    </service>
    Please note: do not override onBind() method, as it will break the functionality of the service.
    "service_name" is a name for your service which will be shown in Security->Notification access.

    2. Handling client update events.
    Now on to implementation of RemoteController.OnClientUpdateListener. .
    You may process everything inside this service, or (which I consider a better alternative, as it gives more flexibility, and you can re-use your service for different apps) re-call methods of external callback to process the client update events.

    Here, however, we will only talk about the methods and which parameters are passed to them.
    The official description is good enough and I recommend reading it before processing further.


    Code:
    [B]onClientChange(boolean clearing)[/B]
    Pretty self-explanatory. "true" will be passed if metadata has to be cleared as there is no valid RemoteControlClient, "false" otherwise.

    Code:
    [B]onClientMetadataUpdate(RemoteController.MetadataEditor metadataEditor)[/B]
    [I]metadataEditor[/I] is a container which has all the available metadata.
    
    How to access it? Very simple.
    For text data, you use RemoteController.MetadataEditor#getString(int key, String defaultValue);
    
    "R.string.unknown" is a reference to String resource with name "unknown", which will be used to replace missing metadata.
    
    To get artist name as a String, use:
    [B]metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_TITLE, getString(R.string.unknown))[/B]
    
    To get title of the song as a String, use:
    [B]metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_ALBUM, getString(R.string.unknown))[/B]
    
    To get the duration of the song as a long, use:
    [B]metadataEditor.getLong(MediaMetadataRetriever.METADATA_KEY_DURATION, 1)[/B]
    1 is the default duration of the song to be used in case the duration is unknown.
    
    To get the artwork as a Bitmap, use:
    [B]metadataEditor.getBitmap(RemoteController.MetadataEditor.BITMAP_KEY_ARTWORK, null)[/B]
    "null" is the default value for the artwork. You may use some placeholder image, however.
    
    And here is one pitfall.
    Naturally, you would expect artist name to be saved with the key MediaMetadataRetriever.METADATA_KEY_ARTIST.
    However, some players, like PowerAmp, save it with key MediaMetadataRetriever.METADATA_KEY_ALBUMARTIS.
    
    So, to avoid unnecessary checks, you may use the following(returns String):
    [B]mArtistText.setText(editor.getString(MediaMetadataRetriever.METADATA_KEY_ARTIST, editor.getString(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST, getString(R.string.unknown))));[/B]
    
    What does it do - it tries to get the artist name by the key METADATA_KEY_ARTIST, and if there is no such String with this key, it will fall back to default value, which, in turn, will try to get the artist name by the key METADATA_KEY_ALBUMARTIST, and if it fails again, it falls back to "unknown" String resource.

    So, you may fetch the metadata using these methods and then process it as you like.

    Code:
    [B]onClientPlaybackStateUpdate(int state, long stateChangeTimeMs, long currentPosMs, float speed)[/B]
    Called when the state of the player has changed.
    Right now this method is not called, probably due to bug.
    [I]state[/I] - playstate of player. Read the [URL="http://developer.android.com/reference/android/media/RemoteControlClient.html"]RemoteControllerClient class description[/URL] to get the list of available playstates.
    For example, RemoteControlClient.PLAYSTATE_PLAYING means that music is currently playing.
    
    [I]stateChangeTimeMs[/I] - the system time at which the change happened.
    
    [I]currentPosMs[/I] - current playback position in milliseconds.
    
    [I]speed[/I] - a speed at which playback occurs. 1.0f is normal playback, 2.0f is 2x-speeded playback, 0.5f is 0.5x-speeded playback etc.

    Code:
    [B]onClientPlaybackStateUpdate (int state)
    [I]state[/I] - playstate of player. Read the [URL="http://developer.android.com/reference/android/media/RemoteControlClient.html"]RemoteControllerClient class description[/URL] to get the list of available playstates.[/B]

    Code:
    [B]onClientTransportControlUpdate (int transportControlFlags)[/B]
    [I]transportControlFlags[/I] - player capabilities in form of bitmask.
    This is one interesting method. It reports the capabilities of current player in form of bitmask.
    Let's say, for example, you want to know if current player supports "fast forward" media key.
    Here is how to do it:
    
    [B]if(transportControlFlags & RemoteControlClient.FLAG_KEY_MEDIA_FAST_FORWARD != 0) doSomethingIfSupport(); else doSomethingIfDoesNotSupport(); [/B]
    
    All of the flags are listed in [URL="http://developer.android.com/reference/android/media/RemoteControlClient.html"]RemoteControlClient class description.[/URL]

    3. Creating RemoteController object.

    The preparations are finished.
    Now we need to construct RemoteController object.

    The constructor of RemoteController takes two arguments. First is Context, and second is RemoteController.OnClientUpdateListener.
    You should know how to fetch Context already.

    Now let's talk about the second parameter. You have to pass YOUR SERVICE implementing RemoteController.OnClientUpdateListener and extending NotificationListenerService. This is a must, otherwise you won't be able to register your RemoteController to the system.

    So, in your service, use something like this:
    Code:
    public class RemoteControlService extends NotificationListenerService implements RemoteController.OnClientUpdateListener {
               private RemoteController mRemoteController;
               private Context mContext;
               ...
               @Override
               public void onCreate() {
                    mContext = getApplicationContext();
                    mRemoteController = new RemoteController(mContext, this);
               }
               ...

    Now to activate our RemoteController we have to register it using AudioManager.
    Please note that AudioManager#registerRemoteController returns "true" in case the registration was successful, and "false" otherwise.
    When can it return "false"? I know only two cases:
    1. You have not activated your NotificationListenerService in Security -> Notification Access.
    2. Your RemoteController.OnClientUpdateListener implementation is not a class extending NotificationListenerService.
    Code:
    if(!((AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE)).registerRemoteController(mRemoteController)) {
        //handle registration failure
    } else {
        mRemoteController.setArtworkConfiguration(BITMAP_WIDTH, BITMAP_HEIGHT);
        setSynchronizationMode(mRemoteController, RemoteController.POSITION_SYNCHRONIZATION_CHECK);
    }

    Of course, we will have to deactivate RemoteController at some point with this code.
    Code:
    ((AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE)).unregisterRemoteController(mRemoteController);

    By default you will NOT receive artwork updates.
    To receive artwork, call setArtworkConfiguration (int, int). First argument is width of the artwork, and second is the height of the artwork.
    Please note that this method can fail, so check if it returns true or false.
    To stop receiving artwork, call clearArtworkConfiguration().

    4. Controlling media playback.

    We can send media key events to RemoteControlClient.
    Also, we can change position of playback for players which support it(currently only Google Play Music supports it).

    You can send key events using this helper method:
    Code:
    private boolean sendKeyEvent(int keyCode) {
                    //send "down" and "up" keyevents.
                    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
                    boolean first = mRemoteController.sendMediaKeyEvent(keyEvent);
                    keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
                    boolean second = mRemoteController.sendMediaKeyEvent(keyEvent);
                    
                    return first && second; //if both  clicks were delivered successfully
    }

    "keyCode" is the code of the pressed media button. For example, sending KeyEvent.KEYCODE_MEDIA_NEXT will cause the player to change track to next. Note that we send both "down" event and "up" method - without that it will get stuck after first command.

    To seek to some position in current song, use RemoteController#seekTo(long). The parameter is the position in the song in milliseconds.
    Please note that it will have no effect if the player does not support remote position control.

    5. Getting current position.
    RIght now the onClientPlaybackStateUpdate(int state, long stateChangeTimeMs, long currentPosMs, float speed) method is broken, as it's not called when the position is updated. So, you have to manually fetch current position. To do this, use the RemoteController#getEstimatedMediaPosition() method - it returns current position in milliseconds(or other values, like 0, if player does not support position update).

    To update it periodically, you may use Handler and Runnable. Look at the implementation on GitHub as the reference.
    1
    Thank you for taking the time to describe the implementation in such detail. My only problem now is including implements RemoteController.OnClientUpdateListener in my NotificationListener class for an app that supports 4.0+. As soon as this service is started up by a 4.3 device the app crashes (reason is obvious, 4.3 doesn't support remote controller). The only solution I've found is to create 2 seperate notification listener classes, one for 4.3 and one for 4.4 (which has the RemoteController code in it). This also creates 2 entries in Notification Access list in the security settings.

    Any ideas on how to make a hybrid service for 4.3/4.4 that implements the necessary RemoteController code?

    I found a solution to this problem (or rather WisdomWolf did). http://stackoverflow.com/questions/...motecontroller-onclientupdatelistener-crashes

    Problem solved :)