Reputation: 1563
I want to develop an Android Service app that dispatches KeyEvents to the foreground application.
Somehow, it would be like this
I cant seem to find a way how, I am only familiar with the activity dispatches KeyEvents to itself, like this:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (event.getKeyCode() == KEYCODE_1) {
// Do something
} else if (event.getKeyCode() == KEYCODE_2) {
// Do something
}
} else if (event.getAction() == KeyEvent.ACTION_UP) {
if (event.getKeyCode() == KEYCODE_1) {
// Do something
return false;
} else if (event.getKeyCode() == KEYCODE_2) {
// Do something
return true;
}
}
return super.dispatchKeyEvent(event);
}
but not with another App.
Correct me if I am wrong, according to what I have researched so far, it says that I need to install my application as a System App and send my keyevents directly to the android system, and the android system will be the one who will send it to the FOREGROUND App. Where it would look more like this:
If this is correct, could anyone help me how to do this? Or if otherwise, please give me a good workaround to achieve my goal. Thanks!
PS: It will be installed on a rooted device
Upvotes: 2
Views: 2542
Reputation: 3645
You can definitely do this with root only and without installing your application as a system app.
The way this can be accomplished is by using uiautomator framework. This is such a powerful framework available for android with the purpose of black box testing applications.
Obviously you are going to use this framework for a slightly different purpose than black box testing, but that's ok.
UiDevice has the method pressKeyCode(int keyCode) that can be used like this to send input to whatever app happends to be in the forground:
UiDevice dev = UiDevice.getInstance();
dev.pressKeyCode(KeyEvent.KEYCODE_1);
The setup to use uiautomator can be a little complex, see this other answer of mine where I describe in more detail what you need to do.
Upvotes: 2