I know you guys are probably tired of these kinds of posts, but why doesn\'t anything happen when I press volume down? I\'m just trying to make a simple code, but apparently
Another approach
@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_DOWN) {
//TODO
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// ... your code
return true;
} else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
// ... your code
return true;
} else
return super.onKeyDown(keyCode, event);
}
I don't know if you can get long press events for the hardware keys.
I've used this code to listen for the volume button before.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
// Do something
}
return true;
}
If that doesn't work for you let us know what device you are testing on.
Kotlin
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
// Do something
}
return true
}
try these. just tested them:
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
super.onKeyLongPress(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
Log.w("LightWriter", "I WORK BRO.");
return true;
}
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
Log.w("LightWriter", "I WORK BRO.");
return true;
}
return true;
}
use this code to handle Volume key event
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
super.onKeyUp(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
Toast.makeText(MainActivity.this,"Up working",Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
Toast.makeText(MainActivity.this,"Down working",Toast.LENGTH_SHORT).show();
return true;
}
return false;
}