Reputation: 41
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!!!
Upvotes: 4
Views: 15091
Reputation: 1974
You can create a BroadcastReceiver that listens to android.intent.action.MEDIA_BUTTON
and register an intent filter to listen to it:
<receiver android:name=".RemoteControlReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
then in your receiver you handle the change:
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.
}
}
}
}
Please take a look at https://developer.android.com/training/managing-audio/volume-playback.html for more information (this code was taken from there)
Edit: fixed KeyEvent key code constant
Upvotes: 0