在关于如何使用硬件播放控制键来控制音频播放的培训部分之后,我创建了一个监听器类:
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");
}
}
}
}
在活动的 onCreate() 中注册它:
private AudioManager mAudioManager;
private ComponentName mRemoteControlReceiver;
...
...
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mRemoteControlReceiver = new ComponentName(this, RemoteControlReceiver.class);
mAudioManager.registerMediaButtonEventReceiver(mRemoteControlReceiver);
并将其注册在清单中:
<receiver android:name=".RemoteControlReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
但是,当按下这些按钮中的任何一个时,不会导致 LogCat 上出现任何日志消息!(无论在播放我的媒体时是否被按下)
我的代码似乎拦截了来自其他媒体播放器的这些事件,但为什么我看不到我的任何Log.e()
消息?我错过了什么?
顺便说一句,当我按下任何这些按钮时,会出现以下消息:
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