Robotium 之跨應(yīng)用操作

新年伊始,干貨不斷

新的一年里,heyniu祝大家心想事成、身體健康、闔家歡樂,還有雞年大吉吧[手動(dòng)滑稽]

眾所周知,Robotium的2大痛處 >> 重簽名、跨應(yīng)用

重簽名: 在我看來這個(gè)不是大問題,找研發(fā)要簽名,然后簽名我們的測試應(yīng)用,就可以保持與被測應(yīng)用簽名的一致性。

跨應(yīng)用:這個(gè)在之前是比較蛋疼的,網(wǎng)上的方案也是大多不適用。今天我就為這個(gè)給大家分享一下我的方案。

靈感來源

? 搶紅包應(yīng)用層出不窮,到底它們是怎樣搶到微信的紅包呢?帶著這個(gè)疑問,查閱了一下資料,發(fā)現(xiàn)它們是通過Android的輔助功能來實(shí)現(xiàn)的,于是我的方案是UiAutomation + Accessibility

重視Robotium

? 2大痛處都解決了,那么優(yōu)勢就來啦,比Appium更快的速度,且與被測應(yīng)用共享數(shù)據(jù) ,這是我選擇它的原因。

原理淺析

? Robotium基于Instrumentation的二次封裝,然而UiAutomation 也能通過instrumentation.getUiAutomation()拿到。順帶提一下Uiautomator也是基于UiAutomation 的封裝。

UiAutomation 跨應(yīng)用操作三大利器:

setOnAccessibilityEventListener() 開啟Accessibility

executeShellCommand() 執(zhí)行shell命令(權(quán)限比Runtime.getRuntime().exec()高,相當(dāng)于adb shell)

injectInputEvent() 注入事件,比如點(diǎn)擊。

Accessibility查找控件的2種方式:

findAccessibilityNodeInfosByViewId() 通過完整的資源查找

findAccessibilityNodeInfosByText() 通過文本查找

以上具體的方法查閱API描述即可。

舉一反三

? 目前已實(shí)現(xiàn)跨應(yīng)用點(diǎn)擊、輸入文本、點(diǎn)擊通知欄、拍照、授權(quán)、QQ登錄等等,其他跨應(yīng)用場景也是類似。只要掌握原理淺析列出的幾個(gè)核心方法,我相信跨應(yīng)用處理已經(jīng)不是問題了,這里只是拋磚引玉。

場景實(shí)例

點(diǎn)擊

/**
     * Work across application boundaries for click.
     * @param x the x coordinate
     * @param y the y coordinate
     */
    public void acrossForClick(float x, float y){
        MotionEvent motionDown = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_DOWN,
                x,  y, 0);
        motionDown.setSource(InputDevice.SOURCE_TOUCHSCREEN);
        uiAutomation.injectInputEvent(motionDown, true);
        MotionEvent motionUp = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_UP,
                x, y, 0);
        motionUp.setSource(InputDevice.SOURCE_TOUCHSCREEN);
        uiAutomation.injectInputEvent(motionUp, true);
        motionUp.recycle();
        motionDown.recycle();
    }

拍照

/**
     * Work across application boundaries for camera.
     * @param viewId The fully qualified resource name of the view id to find. e.g: com.sec.android.app.camera:id/okay
     */
    public void acrossForCamera(String viewId){
        Log.d(LOG_TAG, "acrossForCamera()");
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) return;
        UiAutomation uiAutomation = instrumentation.getUiAutomation();
        uiAutomation.setOnAccessibilityEventListener(new UiAutomation.OnAccessibilityEventListener() {
            @Override
            public void onAccessibilityEvent(AccessibilityEvent event) {
                if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
                    if (viewId.contains(event.getPackageName())) {
                        if (event.getSource() != null) {
                            List<AccessibilityNodeInfo> infoList = event.getSource().findAccessibilityNodeInfosByViewId(viewId);
                            if (infoList == null || infoList.isEmpty()) return;
                            performClick(infoList.get(0));
                        }
                    }
                }
            }
        });
        sleep(2000);
        uiAutomation.executeShellCommand("input keyevent 27");
    }

授權(quán)(核心代碼)

/**
     * Requests permissions to be granted to this application.
     */
    public void requestPermissions(){
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = checkPermissions();
            if (permissions == null || permissions.length == 0) return;
            final String manufacturer = getManufacturer();
            ActivityCompat.requestPermissions((Activity) context, permissions, 10000);
            UiAutomation uiAutomation = instrumentation.getUiAutomation();
            uiAutomation.setOnAccessibilityEventListener(new UiAutomation.OnAccessibilityEventListener() {
                @Override
                public void onAccessibilityEvent(AccessibilityEvent event) {
                    android.util.Log.d(LOG_TAG, "UiAutomation: " + event.toString());
                    if (manufacturer.toLowerCase().contains("mi")) {
                        handlePermissions(event, PACKAGE_INSTALLER_XIAOMI, PERMISSION_ALLOW_ID_XIAOMI);
                    } else handlePermissions(event, PACKAGE_INSTALLER, PERMISSION_ALLOW_ID);
                }
            });
        }
    }

QQ登錄

/**
     * Work across application boundaries for QQ login.
     */
    public void acrossForQQLogin(String account, String password){
        boolean installed = isInstalled(QQ);
        if (!installed) {
            Log.w(LOG_TAG, "QQ is not installed.");
            return;
        }
        uiAutomation.setOnAccessibilityEventListener(new UiAutomation.OnAccessibilityEventListener() {
            @Override
            public void onAccessibilityEvent(AccessibilityEvent event) {
                Log.d(LOG_TAG, "Event: " + event.toString());
                if (event.getEventType() == TYPE_WINDOW_STATE_CHANGED && QQ.contains(event.getPackageName())){
                    handleQQLogin(event, account, password);
                    handleAuthorization(event);
                }
            }
        });
    }

    private void handleAuthorization(AccessibilityEvent event) {
        if (event.getClassName().toString().contains("com.tencent.open.agent.AuthorityActivity")) {
            Log.i(LOG_TAG, "QQ Login: " + event.toString());
            sleep(2000);
            AccessibilityNodeInfo nodeInfo = uiAutomation.getRootInActiveWindow();
            IterationNode(nodeInfo, "android.widget.Button");
        }
    }

    /**
     * Loop through the view and click.
     * @param nodeInfo node
     * @param name class name, e.g: android.widget.Button
     */
    private void IterationNode(AccessibilityNodeInfo nodeInfo, String name) {
        for (int i = 0; i < nodeInfo.getChildCount(); i ++){
            AccessibilityNodeInfo node = nodeInfo.getChild(i);
            Log.i(LOG_TAG, "QQ Login nodeInfo.getChild(i): " + node.getClassName());
            if(name.contains(node.getClassName())) {
                // Click the authorization button.
                performClick(node);
                break;
            } else IterationNode(node, name);
        }
    }

    private void handleQQLogin(AccessibilityEvent event, String account, String password) {
        if (event.getClassName().toString().contains("com.tencent.qqconnect.wtlogin.Login")) {
            AccessibilityNodeInfo nodeInfo = uiAutomation.getRootInActiveWindow();
            List<AccessibilityNodeInfo> infoList = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mobileqq:id/account");
            if (infoList == null || infoList.isEmpty()) return;
            // Click the account edit text and enter text.
            performClick(infoList.get(0));
            acrossForEnterText(account);
            infoList = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mobileqq:id/password");
            if (infoList == null || infoList.isEmpty()) return;
            // Click the password edit text and enter text.
            performClick(infoList.get(0));
            acrossForEnterText(password);
            sleep(4000);
            IterationNode(nodeInfo, "android.widget.Button");
        }
    }

部分演示及完整代碼

百度網(wǎng)盤:鏈接: http://pan.baidu.com/s/1mh6bdJ6 密碼: ffnp

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,288評論 6 342
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,326評論 25 708
  • 一、關(guān)于安卓自動(dòng)化測試 關(guān)于測試自動(dòng)化金字塔,金字塔底端是最基礎(chǔ)的單元測試,再往上是系統(tǒng)接口測試,再往上就是UI自...
    隋胖胖LoveFat閱讀 5,669評論 1 12
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評論 19 139
  • 一.你本周都做了什么事情?周目標(biāo)是什么?完成情況如何? 1.讀完《金錢的靈魂》并簡單輸出 拆書幫21天主題訓(xùn)練營...
    kidII閱讀 132評論 0 1

友情鏈接更多精彩內(nèi)容