Android How to Listen for Volume Button Events

Android How to listen for Volume Button events?

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
}

Listen to volume buttons in background service?

Judging by the couple of other questions about this topic, no.

Other question 1,
Other question 2

Services simply do not receive KeyEvent callbacks.

Android - Volume Buttons used in my application

You need to capture all actions:

@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);
}
}

How to listen for volume up/down key in android with nativescript?

To do that in NativeScript you can use the code provided by James and extend the main activity for your Android NativeScript application. Below I am going to describe the steps needed to achieve that functionality with TypeScript project.

  • Create new file in your app folder called activity.android.ts

  • in the newly created file extend the Activity and overwrite dispatchKeyEvent
    as done here in my demonstration application

  • lastly, provide the new activity to your AndroidManifest file by replacing the default one created by NativeScript

  • build the application and use volume keys - the code will be triggered as expected (in the demo application simple console.log)

The whole demo application demonstrating the technique can be found here.
Article section on how to extend the Android Activity in NativeScript can be found here (both TypeScript and vanilla JavaScript example).

Android Volume Button Listener when Screen Off

No, This is not possible usually because broadcast receiver not work when screen light off because after screen off your volume button get lock and volume level not change.

Alternative Way to do this:

But you can achieve using run Media Player with zero sound in background infinite times that keep your volume button active always or you can use Wake Lock to achieve this.

But I don't suggest to do this method of long time because it totally drain the battery very fast. You can use these alternative method to do this for short period of time otherwise mobile battery get down fastly.



Related Topics



Leave a reply



Submit