如果按一下Headset按钮,android.intent.action.MEDIA_BUTTON事件将触发两次

时间:2015-07-23 05:05:48

标签: java android android-intent broadcastreceiver intentfilter

我已经编写了一个代码,用于在按下耳机媒体按钮时显示Toast。我使用了意图过滤器来执行此操作。但问题是当我按下媒体按钮时它会发射两次。 我的代码是:

MainActivity.java

private MusicIntentReceiver myReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myReceiver=new MusicIntentReceiver();

    ((AudioManager)getSystemService(AUDIO_SERVICE)).registerMediaButtonEventReceiver(new ComponentName(
            this,
            MusicIntentReceiver.class));
}

@Override
public void onResume(){
    IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    IntentFilter filter1=new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
    filter1.setPriority(100);
    registerReceiver(myReceiver, filter);
    registerReceiver(myReceiver,filter1);
    super.onResume();
}

@Override
public void onPause() {
    IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    IntentFilter filter1=new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
    filter1.setPriority(100);
    registerReceiver(myReceiver, filter);
    registerReceiver(myReceiver,filter1);
    super.onPause();
}

BroadcastReceiver.java

public class MusicIntentReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction=intent.getAction();
        Toast.makeText(context, "Action: "+intentAction, Toast.LENGTH_SHORT).show();
        if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
            return;
        }
        Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
        abortBroadcast();
    }
}

1 个答案:

答案 0 :(得分:8)

按钮按下一次,按钮按下一次。

  KeyEvent keyEvent  = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
  if (keyEvent != null) {
      if (event.getAction() == KeyEvent.ACTION_UP)
      {
           switch(keyEvent.getKeyCode()) {
           case KeyEvent.KEYCODE_MEDIA_PLAY:
                  .... &c.
            }
      }
    }