11

I have a requirements in a personal safety app where a user has to launch an app as soon as possible via pressing the volume up or volume down button. What is the procedure to add this functionality?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Muhammad Maqsoodur Rehman
  • 33,681
  • 34
  • 84
  • 124

2 Answers2

14

There is no broadcast event for volume change.

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

Using other buttons (e.g. media buttons) would be possible though.

EDIT: Code sample (using the 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 launching your app.

Community
  • 1
  • 1
molnarm
  • 9,856
  • 2
  • 42
  • 60
  • @MuhammadMaqsoodurRehman I added a code sample (based on my first and second links), I don't have the SDK now so it's not tested. Keep in mind that since this is an unofficial method, it will not work on all devices/versions. – molnarm Jan 20 '14 at 08:49
-6

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
    }
    if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)){
        //Do something
    }
    return true;
}

This method gets event of volume up and down.

Kitkat
  • 77
  • 16
dipali
  • 10,966
  • 5
  • 25
  • 51
  • 1
    hi deepali he wants to launch app itself while this code may work from inside the acticity while before app launch is it possible?? – Jitesh Upadhyay Jan 13 '14 at 08:18
  • @MuhammadMaqsoodurRehman than theres are two posibilities, either you need to do something with firm-ware or else you can launch app first time normally and from the next time you can launch with the help of broadcast receiver. – Jitesh Upadhyay Jan 13 '14 at 09:15