本文介绍了双击检测耳机按钮并长按(单击)Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

双击检测耳机"按钮并长按(单击)Android

Detect Headset buttons double click and Long press(click) 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();

        }

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

It detects the headset button click correctly

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

However how can we detect long click and double click for headset

推荐答案

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

For the double click you can detect it by overriding Activity onKeyDown method and measuring time elapsed between each click:

@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即时,而我在活动中无法检测到

There's also an Activity onKeyLongPress method but it doesn't seem to work on my device with headset button as when I long press headset button it launches Google Now and I can't detect it inside my activity

这篇关于双击检测耳机按钮并长按(单击)Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:26