这是我的here的一个较早版本提出的问题。
我正在运行Android v8的Samsung Galaxy S7上使用android sdk 26,并尝试使用耳机上的播放/暂停按钮(HEADSETHOOK,键码79)。遵循@Commonsware和@Pawel的建议,我在主要活动中注册了接收器,该接收器现在可以正常工作,因为它可以识别何时将耳机从电话中拔出。但是,尽管可以在前台活动中使用onKeyDown时捕获按钮的按下,但BroadcastReceiver并没有将其识别为ACTION_MEDIA_BUTTON(或者据我所知其他任何内容)。发生的一切是,当我长按时会调用默认应用程序(Google助手),而短按时则什么都没有。
这是我的代码(全部包含在一个类中):
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver headsetBtnReceiver;
private AudioManager mAudioManager;
private ComponentName mReceiverComponent;
Intent playerService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
headsetBtnReceiver = new RemoteReceiver();
Log.e("Udp SVC", "Registering Receiver ");
IntentFilter mediaFilter = new IntentFilter();
mediaFilter.setPriority(2148675);
mediaFilter.addAction(Intent.ACTION_HEADSET_PLUG); // <-- Working
mediaFilter.addAction(Intent.ACTION_MEDIA_BUTTON); // <-- Not working
mediaFilter.addAction(Intent.ACTION_SEARCH); // <-- Not working
mediaFilter.addAction(Intent.ACTION_SEARCH_LONG_PRESS); // <-- Not working
registerReceiver(this.headsetBtnReceiver, mediaFilter);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mReceiverComponent = new ComponentName(getApplicationContext(), RemoteReceiver.class);
mAudioManager.registerMediaButtonEventReceiver(mReceiverComponent);
}
@Override
public void onDestroy() {
Log.e("UDP svc", "Destroying MainActivity");
mAudioManager.unregisterMediaButtonEventReceiver(mReceiverComponent);
unregisterReceiver(headsetBtnReceiver);
finish();
super.onDestroy();
}
public static class RemoteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
Log.e("Udp SVC","Into BroadcastReceiver : "+intentAction.toString());
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
final KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event != null && event.getAction() == KeyEvent.KEYCODE_HEADSETHOOK) {
Log.e("Udp SVC","BroadcastReceiver headsethook ");
/***************
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
context.startService(new Intent(context, PlayerService.class));
break;
}
**********/
}
}
}
}
}
如果没有这样的常量,是否可以在IntentFilter中添加特定的键控代码?
帮助!