How to handle double click from headset hook?

1.1k views Asked by At

I would like to control my squash score counter app via only one head set button. It means that I want to detect single or double click and add score to first or second player according to number of clicks.

I cannot use long click, instead of double click, because long click activate Google Now.

2

There are 2 answers

0
Abhishek Balani On BEST ANSWER

This is what I used in my music player to handle headset control single and double click.

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

            }
        }
0
Erick On

Too late, but maybe someone else will find it useful, with triple clicks like Google Music, Spotify, etc.

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

}