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

冷暖自知 提交于 2019-11-27 02:50:24

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21086480/how-can-i-launch-an-android-app-on-upon-pressing-the-volume-up-or-volume-down-bu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!