Android - Listener for hard keys press at background

旧时模样 提交于 2019-11-27 21:41:50
Anup Cowkur

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.

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