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

当按下耳机媒体按钮时,我已经编写了一个显示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();
    }
}

解决方法:

一旦按下按钮,一次按钮按下.

  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.
            }
      }
    }

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...