目标是拦截来自耳机的广播以及最终的蓝牙,以响应来自耳机的不同类型的点击以改变媒体播放器。此解决方案适用于 ICS 之前的所有版本。这是我尝试过的一些代码和事情:
....
private BroadcastReceiver mediaButtonReceiver = new MediaButtonIntentReceiver();
....
public void onCreate() {
...
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
mediaFilter.setPriority(2147483647); // this is bad...I know
this.registerReceiver(mediaButtonReceiver, mediaFilter);
...
}
public class MediaButtonIntentReceiver extends BroadcastReceiver {
private KeyEvent event;
public MediaButtonIntentReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
try {
int action = event.getAction();
switch(action) {
case KeyEvent.ACTION_UP :
Log.d("TEST", "BUTTON UP");
break;
case KeyEvent.ACTION_DOWN :
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE :
Log.d("TEST", "BUTTON DOWN");
break;
}
} catch (Exception e) {
Log.d("TEST", "THIS IS NOT GOOD");
}
abortBroadcast();
}
}
为了尝试使这项工作,听起来 4.0+ 需要这样的东西,但它不起作用:
((AudioManager)getSystemService(AUDIO_SERVICE)).registerMediaButtonEventReceiver(new ComponentName(this, MediaButtonIntentReceiver.class));
除了上述内容之外,我什至尝试将其添加到清单中:
<receiver android:name=".MediaButtonIntentReceiver" android:enabled="true">
<intent-filter android:priority="2147483647" >
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
仍然没有运气。我在这里想念什么?这肯定是 4.0+/ICS/JellyBean 问题...这是在服务中完成的,而不是在活动中完成的。