公司买了台vivo的x21 UDA的测试机,在使用Android Studio安装到手机的时候每次都必须输入密码,还没办法关闭,vivo手机不能root 不能刷机,实在太恶心了。所以想到用AccessibilityService写个辅助功能,在每次安装的时候自动输入密码,并自动完成后面几个按钮点击操作。以前从来没有使用过AccessibilityService,所以在这里记录下。
一 写一个InstallerHelperService继承AccessibilityService
public class InstallerHelperService extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
AccessibilityNodeInfo rootNode = getRootInActiveWindow();
if (rootNode == null) return;
if (event.getPackageName().equals("com.vivo.secime.service")) {
//vivo账号密码
String password = PreferencesUtils.getString(getApplicationContext(),
PreferencesUtils.KEY_PASSWORD, "");
if (!TextUtils.isEmpty(password)) {
fillPassword(rootNode, password);
}
}
findAndClickView(rootNode);
}
/**
* 自动填充密码
*/
private void fillPassword(AccessibilityNodeInfo rootNode, String password) {
AccessibilityNodeInfo editText = rootNode.findFocus(AccessibilityNodeInfo.FOCUS_INPUT);
if (editText == null) return;
if (editText.getPackageName().equals("com.bbk.account")
&& editText.getClassName().equals("android.widget.EditText")) {
Bundle arguments = new Bundle();
arguments.putCharSequence(AccessibilityNodeInfo
.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, password);
editText.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
}
}
/**
* 查找按钮并点击
*/
private void findAndClickView(AccessibilityNodeInfo rootNode) {
List<AccessibilityNodeInfo> nodeInfoList = new ArrayList<>();
nodeInfoList.addAll(rootNode.findAccessibilityNodeInfosByText("确定"));
nodeInfoList.addAll(rootNode.findAccessibilityNodeInfosByText("继续安装"));
nodeInfoList.addAll(rootNode.findAccessibilityNodeInfosByText("安装"));
nodeInfoList.addAll(rootNode.findAccessibilityNodeInfosByText("打开"));
for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
}
@Override
public void onInterrupt() {
}
}
二 创建res/xml/accessibility_config.xml
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackGeneric"
android:canRetrieveWindowContent="true"
android:description="@string/service_desc"
android:notificationTimeout="100"
android:packageNames="com.android.packageinstaller,com.vivo.secime.service" />
这里packageNames 只需要指定android应用安装程序,和vivo的安全校验服务
三 AndroidManifest.xml中注册service
<service
android:name=".InstallerHelperService"
android:enabled="true"
android:exported="true"
android:label="@string/label_service_name"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:process=":BackgroundService">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/accessibility_config" />
</service>
四 使用
安装apk到手机上,设置vivo的安装密码,在辅助功能中打开服务