仅在LG G4(Android版本5.1)上出现此问题。
我的应用程序使用耳机的播放/暂停按钮来触发操作。我将BroadcastReceiver实现为:
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() { super(); }
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
Log.v("MediaButton: ", "Action_Down");
// Some action
}
}
}
我正在注册接收器:
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
filter.setPriority(10000);
registerReceiver(new MediaButtonIntentReceiver(), filter);
此代码适用于各种智能手机,LG G4除外。 Lg手机几乎总是启动音乐小工具,我的logcat说:
01-08 11:49:30.230 22031-22031/com.example.test I/ViewRootImpl: ViewRoot's KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_HEADSETHOOK, scanCode=226, metaState=0, flags=0x8, repeatCount=0, eventTime=285960, downTime=285960, source=0x101 } to com.android.internal.policy.impl.PhoneWindow$DecorView{10cba8ca V.E..... R....... 0,0-1440,2560}
在对SO进行一些搜索之后,我实现了一个MediaSession,使我的应用程序成为ACTION_MEDIA_BUTTON意图的唯一接收者,使用以下代码:
MediaSession mediaSession = new MediaSession(this, "MediaSessionTAG");
mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS);
//Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); // this doesn't work either
Intent mediaButtonIntent = new Intent(getApplicationContext(), MediaButtonIntentReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0);
mediaSession.setMediaButtonReceiver(pIntent);
mediaSession.setActive(true);
如何让我的应用程序成为Media Button intent的唯一接收者,并在每次按钮操作时调用MediaButtonIntentReceiver(BroadcastReceiver)?
答案 0 :(得分:-1)
我有同样的问题,我使用KeyEvent.Callback
解决了它,请参阅示例:
public class MediaButtonIntentReceiver extends Activity{
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
Log.e("buttons","yes master, button pressed is= "+KeyEvent.keyCodeToString(keyCode));
return false;
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
return false;
}
@Override
public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
return false;
}
}