gpt4 book ai didi

java - 在 Android 中使用 BroadcastReceiver 注册耳机按钮单击

转载 作者:IT老高 更新时间:2023-10-28 21:12:24 26 4
gpt4 key购买 nike

我有一个带有单按钮的耳机,并且想在按下按钮时做一个简单的 Toast。

现在我有以下代码:

public class MediaButtonIntentReceiver extends BroadcastReceiver {

public MediaButtonIntentReceiver() {
super();
}

@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
}

我的主要 Activity 如下:

public class mainActivity extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
registerReceiver(r, filter);

}
}

但是当我按下按钮时什么都没有发生。

我很确定 list 中的权限/xml 有问题。到目前为止,这是接收方 XML:

    <receiver android:name=".MediaButtonIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>

....

和:

<uses-permission android:name="android.permission.BLUETOOTH" /> 

我在 LogCat 中注意到,当我按下按钮时,我从“BluetoothIntentReceiver”收到一个错误,说“onReceive() Action : android.intent.action.MEDIA_BUTTON”

最佳答案

只是想回答我自己的问题,以防其他人遇到类似问题。

代码确实有效,只是我没有看到 Toast,因为我安装了另一个耳机按钮 Controller 应用程序(并在后台运行),所以我猜它优先于我的。但是当我把

    IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
filter.setPriority(1000); //this line sets receiver priority
registerReceiver(r, filter);

即使安装了其他应用程序,它也能正常工作。此外,您不需要同时使用上述和 XML,其中一种可以作为注册 Intent 接收器的方式。

关于java - 在 Android 中使用 BroadcastReceiver 注册耳机按钮单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6287116/

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