0

I have an Android service running in the background that receives Key input from the HAL layer. The service should execute DPAD movements UP/DOWN/RIGHT/LEFT/CENTER.

The DPAD directions can be caught but not consumed automatically by the app.

Meanwhile, if I try to inject the same key events using the adb shell input keyevent it works inside the app, works in the sense of they are consumed and executed, if I inject DPAD Right, the focus goes to the right on the app screen.

What is the actual difference between my service injection to the keyevent and the ADB injection of keyevents? Am I missing any permissions?

Here is the code of my service:

private boolean sendKeyEvent(int keycode) {
        boolean bResult = false;
        InputManager im = InputManager.getInstance();
        if (im == null) {
            Log.e(TAG, "Input Manager not available.");
            return false;
        }
       
        KeyEvent evDown = new KeyEvent(1, new Date().getTime(), android.view.KeyEvent.ACTION_DOWN, keycode, 1);
        KeyEvent evUp = new KeyEvent(1, new Date().getTime(), android.view.KeyEvent.ACTION_UP, keycode, 1);

        Log.d(TAG, "sending: keycode: " + keycode);
        boolean retval = im.injectInputEvent(evDown, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
        Log.d(TAG, "injectedInputEvent down returned with: " + retval);
        boolean retval2 = im.injectInputEvent(evUp, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
        Log.d(TAG, "injectedInputEvent up returned with: " + retval2);
        return bResult = retval && retval2;
    }

The service is actually built with the whole system image, so any permissions can be added.

Thanks.

Moaaz Ali
  • 93
  • 15

2 Answers2

1

currently I'm working on an app that uses keyevents through adb commands and I faced this situation, reading some posts, I found that I need to set a INJECT_EVENT permission. But, this permission is only used for system apps, so, the way that I solved this issue is sign my app with custom keys, those keys allows to your app be a kind of system app, read this and this to understand it.

  • Thank you for that. I actually found out that the events are injected successfully, the problem was that apps does not consume these inputs using the functionality I added in my mentioned code. – Moaaz Ali Aug 20 '20 at 07:54
0

I managed to solve the issue by replicating the functionality of adb shell input keyevent that I found here. It works perfectly now. Here is the code:

KeyEvent event = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keycode, 0, 0,
                                  KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0);
im.injectInputEvent(event, InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);

im.injectInputEvent(KeyEvent.changeAction(event, KeyEvent.ACTION_UP),
        InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);

Moaaz Ali
  • 93
  • 15