微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐