我有这个代码来处理来自耳机的按钮点击。问题是我的优先级很低,当我点击按钮时收音机打开。我希望能够优先考虑我的应用。我试图增加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();
}
//其他类中的代码
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);
答案 0 :(得分:3)
您无法为Intent.ACTION_MEDIA_BUTTON
注册registerReceiver
的接收者,因为它由媒体框架单独处理,以按照Responding to Media Buttons guide中的说明发送到正确的媒体应用。
但是,如果您想在前台处理它,则根本不需要使用Intent.ACTION_MEDIA_BUTTON
,因为所有KeyEvent
首先发送到活动Activity
} onKeyDown()
(和onKeyUp()
)。因此,您可以直接处理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);
}