'Android gamepad app to dispatchKeyEvent to another app (game)
I am developing a game controller app for a school project that displays a virtual gamepad and is aimed at controlling any game app on Android. Of course, the game app should support listening to KeyEvents. I am using Java to develop directly for Android.
I found many resources regarding how to handle controller actions and to receive KeyEvents(game side), however it is very hard to find information about the other side - how to actually send those KeyEvents from one application (controller) to another.
What I achieved so far:
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP));
This is the function that I use to dispatch a KeyEvent, I want to move the character one step forward, for example.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
System.out.println("Input received "+ keyCode);
return super.onKeyDown(keyCode, event);
}
I use the code above inside my own controller app to check if I am actually sending and being able to receive the input.
When I run my code and call the dispatchKeyEvent function, I get the console output saying the key input was received by my own application. So it works that way.
The problem is that the input is not working for controlling another app. I leave my controller application dispatching the KeyEvent once every 2 seconds, I quit the app and the console continues logging that the input is being received (by my own application, running on the background) but it does not work when I enter the game app. The game app does not respond to the KeyEvents being dispatched. I tried the game with another virtual controller application and it works fine, so the game is able to receive controller inputs. I also tried removing the KeyEvent listener from my controller app (to see if it was interfering with the KeyEvent reception) but there was no positive result.
So my question is: what is the correct way of sending KeyEvents to Android so that it delivers the inputs to other apps listening? Is this the way that controller key inputs work?
I'd like to thank you in advance for your time.
Solution 1:[1]
Apps like GameKeyboard + can do this but require root to create the virtual gamepad. As far as I know there's no Android API for this so you probably need to use uinput to create a virtual device and generate input events that can be seen by other applications.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | nondebug |