如何处理耳机挂钩的双击?

How to handle double click from headset hook?

我想仅通过一个耳机按钮来控制我的壁球得分计数器应用程序。这意味着我想检测单击或双击并根据点击次数为第一或第二玩家添加分数。

我不能使用长按,而不是双击,因为长按现在激活Google。

这是我在我的音乐播放器中用来处理耳机控制单击和双击的方法。

static final long CLICK_DELAY = 500;
static long lastClick = 0; // oldValue
static long currentClick = System.currentTimeMillis();

@Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)) {

            KeyEvent keyEvent = (KeyEvent) intent.getExtras().get(Intent.EXTRA_KEY_EVENT);

            if (keyEvent.getAction() != KeyEvent.ACTION_DOWN)return;

            lastClick = currentClick ;

            currentClick = System.currentTimeMillis();

            if(currentClick - lastClick < CLICK_DELAY ){

                 //This is double click

            } else { 

                 //This is single click

            }
        }

为时已晚,但也许其他人会发现它有用,点击三次 Google 音乐、Spotify 等

const val DOUBLE_CLICK_TIMEOUT = 430L
private var mHeadsetHookClickCounter = 0

override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean {


    if (Intent.ACTION_MEDIA_BUTTON == mediaButtonEvent?.action) {

        val ke = mediaButtonEvent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)

        if (ke != null && ke.keyCode == KeyEvent.KEYCODE_HEADSETHOOK) {

            if (ke.action == KeyEvent.ACTION_UP) {

                mHeadsetHookClickCounter = min(mHeadsetHookClickCounter+1, 3)

                if (mHeadsetHookClickCounter == 3) {
                    handlingHeadsetClick()
                } else {


                    Handler().postDelayed({

                        handlingHeadsetClick()

                    },  DOUBLE_CLICK_TIMEOUT)

                }


            }

            return true
        }
    }
    return super.onMediaButtonEvent(mediaButtonEvent)
}


private fun handlingHeadsetClick() {

    logd("MediaSessionSupportFeature Handling headset click")

    when(mHeadsetHookClickCounter) {

        1 -> { service.get()?.togglePlayPause() }
        2 -> { service.get()?.playNext() }
        3 -> { service.get()?.playPrevious() }

    }

    // Reset Counter
    mHeadsetHookClickCounter = 0 


    return

}