Android provides some callback methods which help our to handle key event inside the apps. But what if I want to listen key events when my app is running at background? Eg. I want to listen for long press event on search button to do a special feature.
Android - Listener for hard keys press at background
KeyEvents can only be handled by Activities as they are the interface to the user pressing the keys and only when they are in the foreground. Even Services that run in the background are not intended to react on user input.
But by using a service you can have a workaround. You can create a service that responds to hard key press events by registering a BroadcastReceiver. For example in the AOSP music app, they have a Service (MediaPlaybackService) that responds to volume key events by registering a BroadcastReceiver (MediaButtonIntentReceiver).
Here's the code where it registers the receiver:
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
ComponentName rec = new ComponentName(getPackageName(),
MediaButtonIntentReceiver.class.getName());
mAudioManager.registerMediaButtonEventReceiver(rec);
This works even if the Music app is not in the foreground. Code snippet from this answer.
Is this only possible for volume keys or is there a way to do this for arbitrary hardware keys? –
Newspaperwoman
In fact, this doesn't work with volume keys and most of the keys. MediaButtonIntentReceiver is only limited to receive few key events such as: KEYCODE_MEDIA_STOP, KEYCODE_MEDIA_NEXT, etc. –
Lawsuit
© 2022 - 2024 — McMap. All rights reserved.