AccessibilityNodeInfo的生命周期是什么?

时间:2019-07-11 16:47:02

标签: java android accessibilityservice

我正在开发一个包含Accessibility Service的Android应用程序,该应用程序允许用户创建“宏”,该宏可以快速,自动地执行他们已经在使用的第三方应用中经常执行的任务(而不必与某些对讲服务进行交互)他们在等待清单中列出的内容,然后又要反复说出他们想要它做的每一件事。我的问题是,我似乎找不到有关AccessibilityNodeInfo对象的生命周期的详细文档。例如,如果将宏设置为“打开此应用程序,然后单击“执行”按钮,然后列出所有结果”,则可能需要等待并收集应用程序中的增量更新,因为结果可能会涉及多个WINDOW_CONTENT_CHANGED事件,每个应用程序仅包含应用程序正在构建的全部结果列表的一部分。我可以使用诸如findViewById之类的东西来获取所需的元素,但是在多个事件之间保持它们的存在是一个坏主意,因为android操作系统可以随时使它们无效/更改?我想知道是否缺少任何文档/示例,这些文档/示例使我更清楚地了解了如何最好地交互accessibilityNodeInfo对象,以及如何/是否可以随着时间的推移对其进行缓存或收集以更全面,一致地了解其中的内容。该应用的布局。

我看过其他有关accessibilitynodeinfo的帖子,例如(Android AccessibilityNodeInfo refresh() and recycle()),但这仍然无法回答问题,例如节点何时失效,或者如果我不回收节点并以后尝试使用它会发生什么情况(尤其是如果元素已被应用删除)。我要回答的问题在下面的代码中:

//for caching nodes... bad idea?
HashMap<String,AccessibilityNodeInfo> cachedNodes = new HashMap<>();

//gets fired for lots of reasons, can contain arbitrary subsets of the total app layout hierarchy (appears upper bounded by what is visible on the screen)
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    // my accessibility service is listening to all event types
    AccessibilityNodeInfo nodeInfo = event.getSource();
    //sometimes the node is just totally null... why??
    if(nodeInfo != null){
        //what is this really doing? Why is this node sometimes different from traversing up the hierarchy with getParent() manually?
        rootNode = getRootInActiveWindow();
        if(rootNode == null) {
            rootNode = nodeInfo;
            AccessibilityNodeInfo parent = nodeInfo.getParent();
            while(parent != null){
                rootNode = parent;
                parent = rootNode.getParent();
            }
        }
        //It appears this method returns all matches in the event hierarchy regardless of which node you call it on?
        List<AccessibilityNodeInfo> nodesOfInterest = rootNode.findAccessibilityNodeInfosByViewId("package.name/id_of_nodes_i_want");
        for(AccessibilityNodeInfo node: nodesOfInterest){
            //my accessibility service is set up to be able to get view ids and retrieve window content, but view ids are not unique
            // may have to compose an ID based on the view type lineage of the node?
            if(!cachedNodes.containsKey(getUniqueID(node)){
                cachedNodes.put(getUniqueID(node),node);
            }
        }
    }

}

1 个答案:

答案 0 :(得分:0)

AccessibilityNodeInfo or AccessibilityNodeInfoCompat(用于后向兼容性) 不是视图。

当您打开电话的任何屏幕时,其称为Window的内容将显示为可访问性节点信息树。

有时您将AccessibilityNodeInfo设为null,但是刷新后,您可以获得该特定节点的值。

accessibilityNodeInfo.refresh();

以其代表的视图的最新状态刷新此信息。

您可以访问此以获得更多信息。Accessibility Node Info