I'm currently building a streaming Android app and I'm trying to integrate a remote control client (to have for example a control from the lock screen on ICS+).
To do so, I'm doing that at start up in my streaming service:
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
stopSelf();
}
mediaButtonReceiverComponent = new ComponentName(this, RemoteControlReceiver.class);
audioManager.registerMediaButtonEventReceiver(mediaButtonReceiverComponent);
if (remoteControlClientCompat == null) {
final Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setComponent(mediaButtonReceiverComponent);
remoteControlClientCompat = new RemoteControlClientCompat(
PendingIntent.getBroadcast(
getApplicationContext(),
0,
mediaButtonIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
);
RemoteControlHelper.registerRemoteControlClient(audioManager, remoteControlClientCompat);
}
final int flags = RemoteControlClient.FLAG_KEY_MEDIA_STOP;
remoteControlClientCompat.setTransportControlFlags(flags);
remoteControlClientCompat
is simply an instance of RemoteControlClientCompat from the samples.
then during the streaming I'm updating the metadata. everything is working normally, even the controls get sent to my RemoteControlReceiver
. The data and the image appear nicely on the lock screen.
Stopping the streaming from my app destroys the lock screen thing but when I'm trying to destroy it from the widget itself (by pressing the stop button), it's doing something weird. Pressing the stop button makes the broadcast receiver stop my streaming service. Then in the service's onDestroy() method, I'm doing that:
RemoteControlHelper.unregisterRemoteControlClient(audioManager, remoteControlClientCompat);
audioManager.unregisterMediaButtonEventReceiver(mediaButtonReceiverComponent);
audioManager.abandonAudioFocus(this);
The widget goes blinking as soon as audioManager.unregisterMediaButtonEventReceiver(mediaButtonReceiverComponent);
is called. I've tried commenting the line and the blinking happens with audioManager.abandonAudioFocus(this);
. Commenting that other line makes it blink as well when the service stops.
I've noticed this happens too when I'm stopping the streaming from my notification.
What am I doing wrong? I tried changing the order of this calls but I couldn't solve it. I've notice Spotify had the exact same issue a couple of versions ago. I'm wondering how they solved it...
Ok I fixed it. It's simply because the RemoteControlClient cannot be playing when we abandon audio focus. So I just had to call that before destroying anything:
remoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With