gpt4 book ai didi

java - 如果我按一次耳机按钮,android.intent.action.MEDIA_BUTTON 事件会触发两次

转载 作者:太空宇宙 更新时间:2023-11-03 12:05:47 30 4
gpt4 key购买 nike

我已经编写了一段代码来在按下耳机媒体按钮时显示 Toast。我使用了 Intent 过滤器来完成它。但问题是当我按下媒体按钮时它会触发两次。我的代码是:

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

关于java - 如果我按一次耳机按钮,android.intent.action.MEDIA_BUTTON 事件会触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31578544/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com