Question

I'd like to redefine the "volume" button on an android phone. For example,When I press the increase or decrease, the volume will not be change, but only to print a word.

Was it helpful?

Solution

Just override the OnKeyDown method like this:

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

    if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
       //Do whatever you want to do on Volume Up
       return true;
    } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
       //Do whatever you want to do on Volume Down
       return true
    }
    return false;
}

PROTIP: If you want this behaviour on all your activities and not only one, just do this in MainActivity.java (or whatever you want to call it) and make every other Activity extend MainActivity.

PROTIP 2: Don't do this unless it is absolutely necessary and you notify the user it works like that. Android users usually complain about it not having a common behaviour between apps.

OTHER TIPS

You have to override dispatchKeyEvent() method like this:

  @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int action = event.getAction();
        int keyCode = event.getKeyCode();
            switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (action == KeyEvent.ACTION_UP) {
                    //TODO
                    Toast.makeText(this,"Your First Word",Toast.LENGTH_SHORT).show();
                }
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (action == KeyEvent.ACTION_DOWN) {
                    //TODO
                    Toast.makeText(this,"Your Second Word",Toast.LENGTH_SHORT).show();
                }
                return true;
            default:
                return super.dispatchKeyEvent(event);
            }
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top