Raviraj Pophale
Raviraj Pophale

Reputation: 81

How to detect a long press (hold) action on Hardware keys

I am working on a project where I need to detect the pressing of the volume down button as well as the long press of that key. I tried using the methods onKeyDown and on onKeyLongPress. But it isn't working. How can I get around this ?

Upvotes: 1

Views: 5056

Answers (1)

Sanved
Sanved

Reputation: 941

This can be done using flags. You can set up 2 boolean flags which will go on and off according to how the user interacts with the Volume Down key.

PS - you can change the key to Volume up, or any other key by simply placing the KeyEvent id the button carries.

Here is the code -

import android.view.KeyEvent;

boolean shortPress = false;
boolean longPress = false;

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
        Toast.makeText(this, "Long Press", Toast.LENGTH_SHORT).show();
        //Long Press code goes here
        shortPress = false;
        longPress = true;
        return true;
    }
    return super.onKeyLongPress(keyCode, event);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
        event.startTracking();
        if (longPress == true) {
            shortPress = false;
        } else {
            shortPress = true;
            longPress = false;
        }

        return true;
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {

        event.startTracking();
        if (shortPress) {
            Toast.makeText(this, "Short Press", Toast.LENGTH_SHORT).show();
            //Short Press code goes here
        }
        shortPress = true;
        longPress = false;
        return true;
    }

    return super.onKeyUp(keyCode, event);
}

Upvotes: 6

Related Questions