我有这个 ACTION_MEDIA_BUTTON 广播接收器,它实际上适用于 Android 2.x 和 Android 4.1,但出于某种奇怪的原因,在Android 2.x (only)上,我什至得到了两次(单击暂停按钮,当然):
public class RemoteControlReceiver extends BroadcastReceiver {
private static long prevEventTime = 0;
@Override
public void onReceive(Context ctx, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
long curEventTime = event.getEventTime();
if (event != null && (event.getAction() == KeyEvent.ACTION_UP) /*&& (curEventTime != prevEventTime)*/) {
int keycode = event.getKeyCode();
switch (keycode)
{
case KeyEvent.KEYCODE_MEDIA_NEXT:
Log.i(TAG, "KEYCODE_MEDIA_NEXT");
break;
case KeyEvent.KEYCODE_HEADSETHOOK:
Log.i(TAG, "KEYCODE_HEADSETHOOK" + " " + curEventTime + " <> " + prevEventTime + " (" + event.getAction() + ")");
prevEventTime = curEventTime;
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
Log.i(TAG, "KEYCODE_MEDIA_PREVIOUS");
break;
default:
}
}
}
}
}
为了理解其中的奥秘,我记录了每次发生此类事件的事件时间:
03-01 18:27:05.264: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142304436 <> 0 (1)
03-01 18:27:05.434: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142304436 <> 142304436 (1)
03-01 18:27:14.054: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142313265 <> 142304436 (1)
03-01 18:27:14.074: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142313265 <> 142313265 (1)
03-01 18:27:24.254: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142323464 <> 142313265 (1)
03-01 18:27:24.264: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142323464 <> 142323464 (1)
03-01 18:27:37.574: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142336795 <> 142323464 (1)
03-01 18:27:37.614: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142336795 <> 142336795 (1)
03-01 18:27:45.214: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142344433 <> 142336795 (1)
03-01 18:27:45.284: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142344433 <> 142344433 (1)
03-01 18:27:52.474: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142351687 <> 142344433 (1)
03-01 18:27:52.504: I/RemoteControlReceiver.onReceive(22377): KEYCODE_HEADSETHOOK 142351687 <> 142351687 (1)
同样,这种重复出现在 Android 4.1 中不会发生。它只发生在 Android 2.x 中。
知道为什么吗?
(虽然我可以使用相同的事件时间记录技术来过滤第二次发生,但我更愿意先了解发生了什么(我这边可能的编程错误?),然后看看是否有更好的解决方案)
回答以下问题:( “您如何准确注册接收器”)
首先在应用程序的清单中:
<receiver android:name="com.example.mylib.RemoteControlReceiver" android:enabled="true">
<intent-filter android:priority="2147483647" >
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
然后,在我的图书馆活动中(根据这个提示),在 OnCreate() 中:
mRemoteControlReceiver = new ComponentName(this, RemoteControlReceiver.class);
mAudioManager.registerMediaButtonEventReceiver(mRemoteControlReceiver);
我希望这提供了一个更完整的画面,可以帮助解开这个谜团。