[英]How to handle earphones button clicks?
I have this code to handle button clicks from earphones. 我有这段代码可以处理耳机中的按钮单击。 The problem is that my priority is low and when i click the button the radio turns on.
问题是我的优先级低,当我单击按钮时,收音机打开。 I want to be able to give priority to my app.
我希望能够优先处理我的应用。 I tried to increase the setPriority number but it does not work.
我试图增加setPriority的数量,但它不起作用。
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_MULTIPLE) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
//Code in other class //其他类中的代码
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
filter.setPriority(1000); **//increasing this does not work**
registerReceiver(r, filter);
You cannot register a receiver for Intent.ACTION_MEDIA_BUTTON
with registerReceiver
as it is handled separately by the Media framework to dispatch to the correct media app as described in the Responding to Media Buttons guide . 你不能注册一个接收器
Intent.ACTION_MEDIA_BUTTON
与registerReceiver
,因为它是由媒体框架另案处理中所描述的派遣到正确的媒体应用程序响应媒体按钮指南 。
However, in the case where you want to handle it in the foreground, you don't need to use Intent.ACTION_MEDIA_BUTTON
at all as all KeyEvent
s are first sent to the active Activity
via onKeyDown()
(and onKeyUp()
). 但是,如果要在前台处理它,则根本不需要使用
Intent.ACTION_MEDIA_BUTTON
,因为所有KeyEvent
都首先通过onKeyDown()
和onKeyUp()
发送到活动Activity
上。 Therefore you can handle the KeyEvent
directly: 因此,您可以直接处理
KeyEvent
:
@Override
public boolean onKeyDown (int keyCode,
KeyEvent event) {
// This is the center button for headphones
if (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK) {
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onKeyDown(keyCode, event);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.