AccessibilityService使用流程

2018-04-18  本文已影响0人  JFang

1.配置需要的权限

 <!--配置AccessibilityService权限-->
    <uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"
        tools:ignore="ProtectedPermissions" />

2.注册service

<!--注册AccessibilityService-->
        <service android:name=".common.service.InstallAccessibilityService"
            android:label="@string/smart_install"
            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
            <intent-filter>
                <action android:name="android.accessibilityservice.AccessibilityService"/>
            </intent-filter>

            <meta-data
                android:name="android.accessibilityservice"
                android:resource="@xml/accessibility_service_config"/>
        </service>

3.配置Accessibility service info

<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/accessibility_service_description"
    android:packageNames="com.android.packageinstaller"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFlags="flagDefault"
    android:accessibilityFeedbackType="feedbackGeneric"
    android:notificationTimeout="100"
    android:canRetrieveWindowContent="true"

    />

4.实现AccessibilityService

public class InstallAccessibilityService extends AccessibilityService {


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        AccessibilityNodeInfo nodeInfo = accessibilityEvent.getSource();
        if(nodeInfo==null){
            return;
        }

        int eventType = accessibilityEvent.getEventType();
        //监听窗口变化
        if(eventType==AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED||
                eventType== AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED){
            // 中文系统
            click("安装");
            click("下一步");
            click("确定");
            click("完成");
        }

    }

    @Override
    public void onInterrupt() {

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void click(String text){
        AccessibilityNodeInfo rootNodeInfo = getRootInActiveWindow();
        if(rootNodeInfo==null){
            return;
        }
        //如何获取UI元素
        List<AccessibilityNodeInfo> nodeInfos = rootNodeInfo.findAccessibilityNodeInfosByText(text);
        if(nodeInfos==null){
            return;
        }

        for(AccessibilityNodeInfo info :nodeInfos){
            //如果点击按钮并且可以点击
            if(info.getClassName().equals("android.widget.Button")&&info.isClickable()){
                //模拟事件
                info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读