公司買了臺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的安裝密碼,在輔助功能中開啟服務