1

这是我之前的一个问题的后续问题

我在运行 Android v8 的三星 Galaxy S7 上使用 android sdk 26,并尝试使用耳机上的播放/暂停按钮(HEADSETHOOK,键码 79)。根据@Commonsware 和@Pawel 的建议,我从主要活动中注册了接收器,现在它正在工作,因为它可以识别耳机何时从手机上插入/拔出。但是,尽管在前台活动中使用 onKeyDown 时能够捕获按钮按下,但 BroadcastReceiver 并未将其识别为 ACTION_MEDIA_BUTTON (或据我所知的任何其他内容)。所发生的一切是,当我长按时会调用默认应用程序(Google Assistant),而短按则什么都没有。

这是我的代码(全部包含在一个类中):

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;
                 }
                 **********/
            }
        }
    }
}

}

  1. 我做错了什么(如果有的话)?
  2. HEADSETHOOK(键码 79)的 Intent 常量是什么?
  3. 如果没有这样的常量,是否可以向 IntentFilter 添加特定的键码?

  4. 帮助!!

4

0 回答 0