Android - How can a Service App dispatch KeyEvents to another Foreground App

孤街醉人 提交于 2019-12-12 04:49:19

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/27370216/android-how-can-a-service-app-dispatch-keyevents-to-another-foreground-app

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