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.
How to redefine the "volume" button on android
1.4k views Asked by user1421932 At
2
There are 2 answers
1
On
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);
}
}
Just override the OnKeyDown method like this:
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.