How do I change the function of the volume button?

Viewed 46

I'm creating an Android app that counts, like a people counter. Is it possible for it to be in a way where you have to press the volume buttons to add +1 or -1 from the counts?

How do I achieve this?

2 Answers

You should override key behaviour by overriding onKeyDown method in your Activity

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)){
    //Do something
    }
    return super.onKeyDown(keyCode, event);
}

Try this

@Override
public boolean onKeyDown(int keyCode, KeyEvent event){

    if (keyCode == KeyEvent.KEYCODE_VOLUME_UP){
        Toast.makeText(this, "Volume Up", Toast.LENGTH_LONG).show();
        return true;
    }

    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
        Toast.makeText(this, "Volume Down", Toast.LENGTH_LONG).show();
        return true;
    }

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