AccessibilityService是否可以在不打开应用程序的情况下在后台应用程序上执行点击事件

时间:2019-04-16 14:53:22

标签: java android accessibilityservice

从MainActivity中,我正在使用AccessibilityService在另一个应用程序上执行单击事件,当我打开该应用程序并在屏幕上显示该事件时,该事件就可以使用。但是我想执行点击事件而不必打开应用程序,它可以被打开但当前未显示在屏幕上。

这可能吗?

public class DiaryAppAccessibilityService extends AccessibilityService {


@Override
protected void onServiceConnected() {
    super.onServiceConnected();
}

@Override
public void onAccessibilityEvent (AccessibilityEvent event) {


    if (getRootInActiveWindow () == null) {
        return;
    }

    AccessibilityNodeInfoCompat rootInActiveWindow = AccessibilityNodeInfoCompat.wrap (getRootInActiveWindow());

    List<AccessibilityNodeInfoCompat> messageNodeList = rootInActiveWindow.findAccessibilityNodeInfosByViewId ("com.diaryapp:id/entry");
    if (messageNodeList == null || messageNodeList.isEmpty ()) {
        return;
    }

    AccessibilityNodeInfoCompat messageField = messageNodeList.get (0);

    if (messageField.getText () == null || messageField.getText ().length () == 0
            || !messageField.getText ().toString ().endsWith (getApplicationContext ().getString (R.string.diaryapp_suffix))) { // So your service doesn't process any message, but the ones ending your apps suffix
        return;
    }

    List<AccessibilityNodeInfoCompat> sendMessageNodeInfoList = rootInActiveWindow.findAccessibilityNodeInfosByViewId ("com.diaryapp:id/send");
    if (sendMessageNodeInfoList == null || sendMessageNodeInfoList.isEmpty ()) {
        return;
    }

    AccessibilityNodeInfoCompat sendMessageButton = sendMessageNodeInfoList.get (0);


    // Now fire a click on the send button
    sendMessageButton.performAction (AccessibilityNodeInfo.ACTION_CLICK);

    @Override
    public void onInterrupt() {

    }
}

XML配置

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
  android:accessibilityEventTypes="typeWindowContentChanged"
  android:accessibilityFeedbackType="feedbackSpoken"
  android:accessibilityFlags="flagDefault"
  android:notificationTimeout="100"
  android:canRetrieveWindowContent="true"
</accessibility-service>

我删除了此

android:packageNames="com.diaryapp"

因为我希望该服务在其他应用程序中处于活动状态,并且能够从那里执行click事件。

1 个答案:

答案 0 :(得分:1)

您尝试执行的操作并非设计使然。可访问性API旨在帮助残疾人与电话上显示的用户界面进行交互。