How to use MediaSession.setMediaButtonReceiver(PendingIntent) to resume playback

て烟熏妆下的殇ゞ 提交于 2019-12-12 18:15:12

问题


I'm trying to be able to start music playback from my app when the headset buttons are clicked while my app is stopped.

I can use MediaSession.Callback onMediaButtonEvent() or the now deprecated registerMediaButtonEventReceiver() to listen for media button click WHILE my app is playing music, but if I pause the music for a minute, with my Activity and playback Service still running, and then I press the headset button, I see that I have lost the ability to receive the media button broadcast. Instead, Google Now opens.

What I'm trying to do is something like Google Play Music. It is able to start music playback even if the app is completely stopped...no services in the background.

I feel that setMediaButtonReceiver() is the one to use for this, but I've not been able to get it to work.

setMediaButtonReceiver(PendingIntent mbr)

Set a pending intent for your media button receiver to allow restarting playback after the session has been stopped. If your app is started in this way an ACTION_MEDIA_BUTTON intent will be sent via the pending intent.

I have the following snippet in my Service.

PendingIntent pi = PendingIntent.getBroadcast(HeadsetService.this, 0, new Intent(HeadsetService.this, RemoteControlReceiver.class), 0);
mMediaSession.setMediaButtonReceiver(pi);

My RemoteControlReceiver BroadcastReceiver is registered in the Manifest but I receive no broadcast when I press the button.

I've also seen that other music player apps lose the ability to receive media button broadcasts once they've stopped playback for about minute.

Any ideas how I can have a more robust media button controls?

Thanks in advance!

来源:https://stackoverflow.com/questions/39194548/how-to-use-mediasession-setmediabuttonreceiverpendingintent-to-resume-playback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!