[Java for Android App Development] Dr.Alexander_Breen:
Hello, fellow XDA-ers.

Today I want to tell you about new RemoteController class introduced in Android 4.4.

What does this class do?

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):

<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.

[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.

[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.

[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.

[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]

[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:

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.

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.

((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:

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.