How can I launch an android app on upon pressing the volume up or volume down button?
Asked Answered
A

2

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?

Alcaraz answered 13/1, 2014 at 8:8 Comment(2)
really an interesting question!!Flatus
if my answer is feasible than raise and accept that we can close it.Flatus
S
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.

Stationery answered 13/1, 2014 at 9:14 Comment(1)
@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.Stationery
D
-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.

Doge answered 13/1, 2014 at 8:14 Comment(2)
hi deepali he wants to launch app itself while this code may work from inside the acticity while before app launch is it possible??Flatus
@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.Flatus

© 2022 - 2024 — McMap. All rights reserved.