How can I launch an Android app when I press the volume up or down button?

I have requirements in a personal security application where the user should launch the application as soon as possible by pressing the volume up or volume up button. What is the procedure for adding this function?

+6
source share
2 answers

There is no broadcast event to change the volume.

However, there is an undocumented action called android.media.VOLUME_CHANGED_ACTION "that you could use, but it probably won't work on all devices / versions, so it is not recommended .

Using other buttons (e.g. multimedia buttons ) is possible.

EDIT: Sample code (using an undocumented action):

AndroidManifest.xml

 ... <receiver android:name="VolumeChangeReceiver" > <intent-filter> <action android:name="android.media.VOLUME_CHANGED_ACTION" /> </intent-filter> </receiver> ... 

VolumeChangeReceiver.java

 public class VolumeChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) { int newVolume = intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_VALUE", 0); int oldVolume = intent.getIntExtra("android.media.EXTRA_PREV_VOLUME_STREAM_VALUE", 0); if (newVolume != oldVolume) { Intent i = new Intent(); i.setClass(context, YourActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } } } } 

See this question if you want to unlock the screen when the application starts.

+9
source

I used this code to listen to the volume button before,

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

This method receives an increase and decrease volume event.

-5
source

All Articles