Detect Headset buttons double click and Long press(click) Android
Asked Answered
C

1

0

Detect Headset buttons double click and Long press(click) Android

I am trying the bellow code

 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

Cist answered 23/3, 2016 at 7:45 Comment(0)
O
0

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);
}

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

Owing answered 22/1, 2017 at 12:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.