Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

以 AccessibilityService 為基礎,拆解 Android 自動化操作的三個環節

編輯:關於 Android 程式設計

本文以「自動處理聊天中的紅包消息」為案例,說明 Android 無障礙服務(AccessibilityService)在自動化場景下的完整用法:監聽畫面變化、定位目標控制項、模擬點擊、記錄結果。這些技術本身是中性的,同樣的手法也被廣泛應用於自動化測試、輔助功能工具與批量操作腳本。

功能目標

1. 畫面上出現可領取的消息時,自動完成點開與領取;
2. 停留在桌面或聊天列表時,收到相關通知能自動跳進對應對話;
3. 提供操作日誌,把每次處理的結果落庫保存。

技術選型

AccessibilityService——系統提供的無障礙服務框架,可以監聽視窗與通知事件、讀取當前視窗的節點樹,並對節點執行點擊等動作。這是實現上述自動化最核心的能力。
ActiveAndroid——一個輕量 ORM,用來把日誌寫進 SQLite。
SharedPreferences——保存使用者的監控開關等偏好設定。

介面配置

在 res/xml/accessibility_service_config.xml 中宣告服務能力:

<accessibility-service xmlns:android="https://schemas.android.com/apk/res/android"
    android:accessibilityEventTypes="typeNotificationStateChanged|typeWindowStateChanged|typeWindowContentChanged"
    android:accessibilityFeedbackType="feedbackGeneric"
    android:accessibilityFlags="flagDefault"
    android:canRetrieveWindowContent="true"
    android:description="@string/accessibility_description"
    android:notificationTimeout="100"
    android:packageNames="com.tencent.mm"
    android:settingsActivity="com.oden.annotations.app.activity.ManActivity" />

幾個關鍵欄位的含義:accessibilityEventTypes 決定訂閱哪些事件類型;packageNames 限定只關心目標應用的包名,避免被其他應用的畫面變化干擾;canRetrieveWindowContent 必須為 true,否則讀不到節點樹;notificationTimeout 是事件去抖的閾值,單位毫秒。

接著在 AndroidManifest.xml 註冊服務,並加上 BIND_ACCESSIBILITY_SERVICE 權限:

<service android:name=".app.service.HongbaoService_"
    android:enabled="true"
    android:exported="true"
    android:label="@string/app_name"
    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>

事件分派總入口

所有系統事件都匯流到 onAccessibilityEvent。這裡的做法是先依使用者開關決定走哪條分支,再用一組 boolean 標誌驅動後續動作,形成一個小型狀態機:

private static final String GET_RED_PACKET        = "領取紅包";
private static final String CHECK_RED_PACKET      = "查看紅包";
private static final String RED_PACKET_PICKED     = "手慢了,紅包派完了";
private static final String RED_PACKET_PICKED2    = "手氣";
private static final String RED_PACKET_PICKED_DETAIL = "紅包詳情";
private static final String RED_PACKET_SAVE       = "已存入零錢";
private static final String RED_PACKET_NOTIFICATION = "[微信紅包]";

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    if (watchedFlags == null) return;

    // 通知欄與聊天列表兩條監聽通道
    if (!mMutex) {
        if (watchedFlags.get("pref_watch_notification") && watchNotifications(event)) return;
        if (watchedFlags.get("pref_watch_list") && watchList(event)) return;
    }
    if (!watchedFlags.get("pref_watch_chat")) return;

    this.rootNodeInfo = event.getSource();
    if (rootNodeInfo == null) return;
    mReceiveNode = null;
    mUnpackNode = null;
    checkNodeInfo();

    // 已偵測到可領取,尚未點開
    if (mLuckyMoneyReceived && !mLuckyMoneyPicked && mReceiveNode != null) {
        mMutex = true;
        AccessibilityNodeInfo cellNode = mReceiveNode;
        cellNode.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
        mLuckyMoneyReceived = false;
        mLuckyMoneyPicked = true;
    }

    // 已點開,尚未領取
    if (mNeedUnpack && mUnpackNode != null) {
        AccessibilityNodeInfo cellNode = mUnpackNode;
        cellNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        mNeedUnpack = false;
    }

    // 收尾:返回上一頁並統計
    if (mNeedBack) {
        performGlobalAction(GLOBAL_ACTION_BACK);
        mMutex = false;
        mNeedBack = false;
        if (isGetMoney) {
            totalMoney += gotMoney;
            totalSuccessNum++;
            myPrefs.totalMoney().put(totalMoney);
            myPrefs.successNum().put(totalSuccessNum);
            saveToLog(hongbaoInfo);
            isGetMoney = false;
        }
    }
}

節點檢測:如何在混亂的視窗樹中定位目標

這是整個方案最需要小心的地方。聊天視窗裡文字、圖片、按鈕混雜,單純用關鍵字搜尋很容易誤命中普通聊天文字。這裡用了兩層防護:一是檢查目標節點的父容器是否為 LinearLayout,二是用一個 signature 校驗節點結構:

private void checkNodeInfo() {
    if (this.rootNodeInfo == null) return;

    // 聊天視窗:尋找「領取紅包」或「查看紅包」
    List<AccessibilityNodeInfo> nodes1 = this.findAccessibilityNodeInfosByTexts(
            this.rootNodeInfo, new String[]{ GET_RED_PACKET, CHECK_RED_PACKET });
    if (!nodes1.isEmpty()) {
        AccessibilityNodeInfo targetNode = nodes1.get(nodes1.size() - 1);
        // 過濾掉純文字訊息造成的誤判
        if ("android.widget.LinearLayout".equals(targetNode.getParent().getClassName())) {
            if (this.signature.generateSignature(targetNode)) {
                mLuckyMoneyReceived = true;
                mReceiveNode = targetNode;
            }
        }
        return;
    }

    // 已進入詳情頁:尋找「拆紅包」按鈕
    List<AccessibilityNodeInfo> nodes2 = this.findAccessibilityNodeInfosByTexts(
            this.rootNodeInfo, new String[]{ "拆紅包" });
    if (!nodes2.isEmpty()) {
        for (AccessibilityNodeInfo nodeInfo : nodes2) {
            if (nodeInfo.getClassName().equals("android.widget.Button")) {
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        }
    } else {
        // 相容不同版本:部分版本按鈕位置固定在第 4 個子節點
        AccessibilityNodeInfo node2 =
                (this.rootNodeInfo.getChildCount() > 3) ? this.rootNodeInfo.getChild(3) : null;
        if (node2 != null && node2.getClassName().equals("android.widget.Button")) {
            mUnpackNode = node2;
            mNeedUnpack = true;
            isToGetMoney = true;
            return;
        }
    }

    // 收尾判斷:已領取完畢 / 已存入零錢 / 別人已搶完
    if (mLuckyMoneyPicked) {
        List<AccessibilityNodeInfo> nodes3 = this.findAccessibilityNodeInfosByTexts(
                this.rootNodeInfo, new String[] {
                        RED_PACKET_PICKED, RED_PACKET_SAVE,
                        RED_PACKET_PICKED2, RED_PACKET_PICKED_DETAIL });
        if (!nodes3.isEmpty()) {
            if (rootNodeInfo.getChildCount() > 1) {
                // 詳情頁尚未準備好,放棄本輪
            } else {
                String text = nodes3.get(0).getText().toString();
                if (!text.equals(RED_PACKET_PICKED_DETAIL)) {
                    AccessibilityNodeInfo targetNode = nodes3.get(nodes3.size() - 1);
                    hongbaoInfo.getInfo(targetNode);
                    if (isToGetMoney) {
                        isGetMoney = true;
                        isToGetMoney = false;
                        gotMoney = hongbaoInfo.getMoney();
                    }
                }
            }
            mNeedBack = true;
            mLuckyMoneyPicked = false;
        }
    }
}

這段程式透露出一個實務上的重要經驗:依賴文字比對的自動化腳本非常脆弱,目標應用一改版就可能失效。因此除了關鍵字,最好再加上控件類型、父容器類型、節點位置等多重條件交叉驗證,並為不同版本預留相容分支。

另外兩條監聽通道

監聽聊天列表——停在列表頁時,透過 contentDescription 判斷是否有新消息,並用「上次描述」做去重,避免同一條被反覆點擊:

private boolean watchList(AccessibilityEvent event) {
    if (event.getEventType() != AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
            || event.getSource() == null) return false;
    List<AccessibilityNodeInfo> nodes =
            event.getSource().findAccessibilityNodeInfosByText(RED_PACKET_NOTIFICATION);
    if (!nodes.isEmpty()) {
        AccessibilityNodeInfo nodeToClick = nodes.get(0);
        CharSequence desc = nodeToClick.getContentDescription();
        if (desc != null && !lastContentDescription.equals(desc)) {
            nodeToClick.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            lastContentDescription = desc.toString();
            return true;
        }
    }
    return false;
}

監聽通知欄——直接從 Notification 的 contentIntent 跳轉:

private boolean watchNotifications(AccessibilityEvent event) {
    if (event.getEventType() != AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) return false;
    String tip = event.getText().toString();
    if (!tip.contains(RED_PACKET_NOTIFICATION)) return true;
    Parcelable p = event.getParcelableData();
    if (p instanceof Notification) {
        Notification n = (Notification) p;
        try {
            n.contentIntent.send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }
    return true;
}

資料落庫

用 ActiveAndroid 定義一張簡單的表,把發送者、金額與時間存下來:

@Table(name = "HongbaoInfos")
public class HongbaoInfo extends Model {

    private int month, day, hour, min, sec;

    @Column(name = "sender") public String sender;
    @Column(name = "money")  public String money;
    @Column(name = "time")   public String time;

    /** 從節點的父層級依序取出發送者與金額 */
    public void getInfo(AccessibilityNodeInfo node) {
        AccessibilityNodeInfo hongbaoNode = node.getParent();
        sender = hongbaoNode.getChild(0).getText().toString();
        money  = hongbaoNode.getChild(2).getText().toString();
        time   = getStringTime();
    }

    private String getStringTime() {
        Calendar c = Calendar.getInstance();
        month = c.get(Calendar.MONTH) + 1;
        day   = c.get(Calendar.DAY_OF_MONTH);
        hour  = c.get(Calendar.HOUR_OF_DAY);
        min   = c.get(Calendar.MINUTE);
        sec   = c.get(Calendar.SECOND);
        return month + "月" + day + "日 " + hour + ":" + min + ":" + sec;
    }

    public float getMoney()   { return Float.parseFloat(money); }
    public String getSender() { return sender; }
    public String getTime()   { return time; }

    public static List<HongbaoInfo> getAll() {
        return new Select().from(HongbaoInfo.class).orderBy("Id ASC").execute();
    }
    public static void deleteALL() {
        new Delete().from(HongbaoInfo.class).execute();
    }

    @Override
    public String toString() {
        return "HongbaoInfo [sender=" + sender + ", money=" + money + ", time=" + time + "]";
    }
}
private void saveToLog(HongbaoInfo hongbaoInfo) {
    if (watchedFlags.get("pref_etc_log")) {
        hongbaoInfo.save();
    }
}

已知限制與實務提醒

這個方案在測試機上可以正常運作,但有兩個結構性問題值得記住:

去重造成的漏抓。 為了避免同一條消息被反覆點擊,程式對相同 contentDescription 做了過濾,結果同一發送者連續發送時,第二個之後可能不會觸發。若要改善,需要把去重鍵設計得更細緻,例如加入時間戳或節點指紋。

服務被系統回收。 AccessibilityService 長時間運行後有時會被系統終止,需要重新到設定頁手動開啟。這也是所有依賴無障礙服務的常駐型工具共同的痛點。

更根本的一點:這類腳本與目標應用的版本強耦合,一旦對方調整介面結構或加入檢測,功能就會失效。因此它適合當作學習 AccessibilityService 的練習題,而不適合當作長期依賴的生產方案。若目的只是自動化測試,UI Automator 或 Espresso 是更穩定的選擇。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved