4

I am new to android and I extensively searched for this. Any help would be much appreciated:) I have a requirement for an application which does the following:

An application that runs in the background as a service that listens to the volume key(UP/Down). On this event an activity will be displayed in foreground.

[I am able to do this from an Activity, however the activity has to be at the foreground and only after I press the volume button I get a toast.]

Please HELP!!!

4

1 回答 1

0

您可以创建一个 BroadcastReceiver 来监听android.intent.action.MEDIA_BUTTON并注册一个意图过滤器来监听它:

<receiver android:name=".RemoteControlReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

然后在您的接收器中处理更改:

public class RemoteControlReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
            KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            if (KeyEvent.KEYCODE_VOLUME_DOWN == event.getKeyCode()) {
                // Handle key press.
            }
        }
    }
}

请查看https://developer.android.com/training/managing-audio/volume-playback.html了解更多信息(此代码取自那里)

编辑:固定 KeyEvent 键码常量

于 2013-10-13T13:38:45.837 回答