Why does ACTION_MEDIA_BUTTON fail to process event

2019-02-28 02:35发布

问题:

Following the training section on how to use hardware playback control keys to control audio playback, I create a listener class:

public class RemoteControlReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context arg0, Intent intent) {
        if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
            KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            Log.e(TAG, "ACTION_MEDIA_BUTTON"); 

            int keycode = event.getKeyCode();
            switch (keycode)
            {
                case KeyEvent.KEYCODE_MEDIA_NEXT:
                    Log.e(TAG, "KEYCODE_MEDIA_NEXT"); 
                    break;
                case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
                    Log.e(TAG, "KEYCODE_MEDIA_PLAY_PAUSE"); 
                    break;
                case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
                    Log.e(TAG, "KEYCODE_MEDIA_PREVIOUS"); 
                    break;
                default:
            }

            if (/*KeyEvent.KEYCODE_MEDIA_PLAY*/ 126 == event.getKeyCode()) { // KEYCODE_MEDIA_PLAY undefined for API < 11
                Log.e(TAG, "KEYCODE_MEDIA_PLAY"); 
            }           
        }
    }
}

Registered it in activity's onCreate():

private AudioManager mAudioManager;
private ComponentName mRemoteControlReceiver;
...
...
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mRemoteControlReceiver = new ComponentName(this, RemoteControlReceiver.class);
mAudioManager.registerMediaButtonEventReceiver(mRemoteControlReceiver);

And registered it in the manifest:

<receiver android:name=".RemoteControlReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

But when pressing any of these buttons does not result in any of the log message appearing on LogCat! (regardless whether being pressed while playing my media or not)

My codes seem to intercept these events from other media players, but why can't I see any of my Log.e() messages? What am I missing?

BTW, when I press any of those buttons, the following messages appear instead:

W/KeyCharacterMap(19801): Can't open keycharmap file
W/KeyCharacterMap(19801): Error loading keycharmap file '/system/usr/keychars/h2w_headset.kcm.bin'. hw.keyboards.131075.devname='h2w headset'
W/KeyCharacterMap(19801): Using default keymap: /system/usr/keychars/qwerty.kcm.bin

回答1:

Do you happen to use Library Project to implement this?

If so, which manifest did you put the <receiver> in? The library's or the application's?

If you put in the library's, it won't work. You must place this in the application's manifest:

<receiver android:name=".RemoteControlReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>