Home > Back-end >  android Keyevent: long press and normal press (not able to make it work as wanted)
android Keyevent: long press and normal press (not able to make it work as wanted)

Time:01-18

I am trying to create a left key press action for my TV app.

My remote has left/right up and down keys

I want to run two different function when normal press and long press.

I am trying the following

If I press long press it just does the action of normal press more times.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (event.isLongPress()) {
                    goBackward();
                    return true;
                }else{
                    goBackward2();
                }
                return true;
            default:
                return super.onKeyDown(keyCode, event);

How can I do this.

CodePudding user response:

By observation, when a DPAD key is pressing, multiple times of key down events are dispatched. (i.e., discrete events of key down)

So in order to detect a long press of KEY_CODE_DPAD_LEFT, you will need to calculate the duration by yourself. And then determine how long a button pressed is long to you. (e.g., 5 seconds)

To calculate the duration, you will need to detect:

  1. When do someone press the key
  2. When do someone leave the key

I believe both the overide methods onKeyDown and onKeyUp have the ability to do so, so here is an example that I have just written.

Example

  • To detect key down start time (KeyEvent.KEYCODE_DPAD_LEFT), we will need an instance variable
    long mKeyDownStartTime = 0;
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            startKeyDown(SystemClock.elapsedRealtime());
        }
        return super.onKeyDown(keyCode, event);
    }

    private void startKeyDown(long startKeyDownTime) {
        if (mKeyDownStartTime == 0) { // this is added to prevent identical discrete key down event reset the value
            mKeyDownStartTime = startKeyDownTime;
        }
    }
  • To calculate the key down duration WHEN key up event occurs
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            endKeyDown(SystemClock.elapsedRealtime());
        }
        return super.onKeyUp(keyCode, event);
    }

    private void endKeyDown(long endKeyDownTime) {
        long pressDuration = endKeyDownTime - mKeyDownStartTime;
        mKeyDownStartTime = 0; // reset to zero to allow startKeyDown() set the value in again
        Log.d(TAG, "endKeyDown: [ keyPressDuration="   pressDuration   " ]");

        if (pressDuration > 5000) {
            Log.d(TAG, "endKeyDown: LONG press of DPAD_LEFT detected");
        } else {
            Log.d(TAG, "endKeyDown: SHORT press of DPAD_LEFT detected");
        }
    }
  • Related