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

不想你离开。 提交于 2019-12-12 02:54:29

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/36172380/detect-headset-buttons-double-click-and-long-pressclick-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!