Reputation: 3880
I'm using AccessibilityService OnKeyEvent to capture the Headsethook. This is so I can trigger an event on key up, and key down, even if my app it not in focus.
However, it does not work once the screen goes off. Is there any way around this?
Upvotes: 3
Views: 1907
Reputation: 41
AccessibilityService
will not work when the screen is off. so to achieve the effort that catch KeyEvent
when power down, You should use other alternatives.
if you only want to catch HEADSETHOOK
, you can use MediaButtonIntentReceiver
instead of AccessibilityService
: register a BroadcastReceiver
to receive ACTION_MEDIA_BUTTON
intent, so can catch KEYCODE_MEDIA_*
and KEYCODE_HEADSETHOOK
in background, also as the screen is off.
AndroidManifest.xml
<receiver android:name="com.exmaple.MediaButtonReceiver"><intent-filter >
<action android:name="android.intent.action.MEDIA_BUTTON"></action>
</intent-filter></receiver>
MediaButtonReceiver.java
...
public void onReceive(Context context, Intent intent) {
...
KeyEvent keyEvent = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
int keyCode = keyEvent.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_HEADSETHOOK:
...
}
}
...
}
if you do not want the other app to catch HEADSETHOOK
, you should use AudioManager
to register it:
...
AudioManager mAudioManager =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
ComponentName mbCN = new ComponentName(getPackageName(),MediaButtonIntentReceiver.class.getName());
mAudioManager.registerMediaButtonEventReceiver(mbCN);
...
//mAudioManager.unregisterMediaButtonEventReceiver(mbCN);
...
note: most music player apps also use MediaButton
, when they register MediaButton
receiver, your app will lose the focus of AudioManager
, so you maybe should use AudioFocusChangeListener
to listen the focus change and re-register.
if you also want to capture other keys in background. as far as i know, root is an all-right solution. you can use getevent
command to catch all the log stream of input devices. then trigger the log of wanted keys.
Upvotes: 3