繁体   English   中英

如何处理耳机按钮的喀哒声?

[英]How to handle earphones button clicks?

我有这段代码可以处理耳机中的按钮单击。 问题是我的优先级低,当我单击按钮时,收音机打开。 我希望能够优先处理我的应用。 我试图增加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);

你不能注册一个接收器Intent.ACTION_MEDIA_BUTTONregisterReceiver ,因为它是由媒体框架另案处理中所描述的派遣到正确的媒体应用程序响应媒体按钮指南

但是,如果要在前台处理它,则根本不需要使用Intent.ACTION_MEDIA_BUTTON ,因为所有KeyEvent都首先通过onKeyDown()onKeyUp()发送到活动Activity上。 因此,您可以直接处理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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM