Android MediaSession not reacting to headphones

两盒软妹~` 提交于 2020-01-17 05:37:51

问题


I'm quite new to android and I'm creating a Music Player. I wasn't familiar with MediaSession and now I have a functioning Music Player but it does not support reacting to headphones clicks or pausing on incomming calls.

This is my code:

    ComponentName mediaButtonReceiver = new ComponentName(context, MusicPlayerNotificationReceiver.class);
    final MediaSessionCompat mediaSession = new MediaSessionCompat(context, "Start MP", mediaButtonReceiver, null);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    LockerActivity.getInstance().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mediaSession.setCallback(MusicPlayer.this);
        }
    });
    mediaSession.setActive(true);

I also have a BroadcastReceiver that is defined with this action

<action android:name="android.intent.action.MEDIA_BUTTON" />

This is all of my code ralated to MediaSession. So, for now, i just try to get notified for an action from the headphones. I have a breakpoint on the first line inside onReceive() and i click on the button in headphones and nothing happens. If i long click on the button than android goes into Listening mode for speak instructions.

What else do i need?


回答1:


First I've made all the calls to MediaSession to run on ui thread then I've added this code from google training:

AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
...

// Start listening for button presses
am.registerMediaButtonEventReceiver(RemoteControlReceiver);
...

// Stop listening for button presses
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);

http://developer.android.com/training/managing-audio/volume-playback.html#PlaybackControls

and i saw the callbacks defined in this SO answer: How to use the new MediaSession class to receive media button presses on Android 5.x?

BTW, It is catched on the MediaSession.Callback and not in the BroadcastReceiver.



来源:https://stackoverflow.com/questions/33596223/android-mediasession-not-reacting-to-headphones

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