目標是最終攔截來自耳機以及藍牙的廣播,以響應來自耳機的不同類型的點擊以更改媒體播放器。此解決方案適用於ICS之前的所有版本。下面是一些代碼,事情我已經試過的:MediaButtonIntentReceiver無法在Android 4.0及更高版本中工作
....
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 /果凍豆的問題......這是在一項服務中完成的,而不是一項活動。
我也發現這是Android核心的原因,但沒有辦法解決它:http://code.google.com/p/media-button-router/issues/detail?id=10#c4 – Du3