【问题标题】:Detect Headset buttons double click and Long press(click) Android检测耳机按钮双击和长按(点击)Android
【发布时间】:2016-03-23 07:45:37
【问题描述】:

检测耳机按钮双击和长按(点击)Android

我正在尝试下面的代码

 public class MediaButtonReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("----onReceive--", " ");

            if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {

                Log.e("----jack out--", " ");

                if (intent.getExtras().getInt("state") == 1)// if plugged
                    Toast.makeText(context, "earphones plugged", Toast.LENGTH_LONG)
                            .show();
                else
                    Toast.makeText(context, "earphones un-plugged",
                            Toast.LENGTH_LONG).show();
            }

            if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
                Toast.makeText(context, "button pressed", Toast.LENGTH_LONG).show();
                // key=intent.getExtras().getString("EXTRA_KEY_EVENT");

            }

            abortBroadcast();

        }

它检测到耳机按钮点击正确

但是我们如何检测耳机的长按和双击

【问题讨论】:

    标签: android headset


    【解决方案1】:

    对于双击,您可以通过覆盖 Activity onKeyDown 方法并测量每次点击之间经过的时间来检测它:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_HEADSETHOOK){
            //check if it's the first or the second click and measure time between them
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    

    还有一个 Activity onKeyLongPress 方法,但它似乎不适用于带有耳机按钮的设备,因为当我长按耳机按钮时,它会启动 Google Now,但我无法在我的活动中检测到它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2016-04-05
      • 2013-05-03
      相关资源
      最近更新 更多