简体   繁体   English

Android-服务应用程序如何将KeyEvent调度到另一个前景应用程序

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

I want to develop an Android Service app that dispatches KeyEvents to the foreground application. 我想开发一个Android服务应用程序,该应用程序将KeyEvents调度到前台应用程序。

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: 我似乎找不到一种方法,我只熟悉该活动向其本身分配KeyEvent,如下所示:

@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. 如果我错了,请纠正我,根据到目前为止的研究,它说我需要将我的应用程序安装为系统应用程序,并将关键事件直接发送到android系统,而android系统将是发送该事件的人它到FOREGROUND应用程序。 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 PS:它将安装在有根设备上

You can definitely do this with root only and without installing your application as a system app. 您绝对可以仅使用root来执行此操作,而无需将应用程序安装为系统应用程序。

The way this can be accomplished is by using uiautomator framework . 可以通过使用uiautomator框架来实现。 This is such a powerful framework available for android with the purpose of black box testing applications. 这是一个功能强大的框架,可用于android,以进行黑匣子测试应用程序。

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具有方法pressKeyCode(int keyCode) ,可以像这样使用该方法将输入发送到碰巧在前台的任何应用程序:

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. 使用uiautomator的设置可能有些复杂,请参阅我的其他答案 ,在此我将更详细地描述您需要执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM