通過adb shell dumpsys命令獲取當前應用的component

在android測試中,經常需要知道啓動一個Activity所需要的component,例如在monkeyrunner中啓動一個系統設置:startActivity(component="com.android.settings/com.android.settings.Settings"),那如何獲取該component 呢?

有如下方法:

1.在有root 權限並且開啓了view server 的前提下,使用sdk/tools目錄下hierarchyviewer.bat 工具可以獲得

2.在sdk/build-tools目錄下有個aapt工具,使用aapt dump badging *.apk可以獲得

3.在CMD窗口中執行adb logcat -v time -s ActivityManager,然後點擊應用進入,如點擊系統設置,進入後會有相應的日誌信息打印出來,在信息中查找 cmp=com.android.settings/.Settings

4.通過adb shell dumpsys命令獲得,這也是我準備主要介紹的方法

在CMD窗口中執行adb shell dumpsys window -h,會顯示下面的幫助內容:

C:\Users\xuxu>adb shell dumpsys window -h
Window manager dump options:
[-a] [-h] [cmd] ...
cmd may be one of:
l[astanr]: last ANR information
p[policy]: policy state
a[animator]: animator state
s[essions]: active sessions
d[isplays]: active display contents
 t[okens]: token list
w[indows]: window list
cmd may also be a NAME to dump windows.  NAME may
be a partial substring in a window name, a
Window hex object identifier, or
 "all" for all windows, or
 "visible" for the visible windows.
 -a: include all available server state.

我們使用windows選項,執行adb shell dumpsys window w,在輸出結果中我們可以找到打開的當前應用的component,而component中總是含有斜槓“/”,所以我們可以使用這個命令得到輸出(進入系統設置應用),adb shell dumpsys window w | findstr \/ ,需要轉義斜槓“/”,在linux下需要把findstr換成grep,此時輸出的內容還是會比較多,不容易查找,再結果分析,發現可以再查找字符串“name=”,

接下來重新執行adb shell dumpsys window w | findstr \/ | findstr name= ,會輸出下面的結果:

C:\Users\xuxu>adb shell dumpsys window w | findstr \/ | findstr name=
      mSurface=Surface(
name=com.android.settings/com.android.settings.Settings)

com.android.settings/com.android.settings.Settings 就是我們需要的component

接下來用python語句來獲取該component:

import os
import re

def getFocusedPackageAndActivity():

        pattern = re.compile(r"[a-zA-Z0-9\.]+/[a-zA-Z0-9\.]+")
        out = os.popen("adb shell dumpsys window windows | findstr \/ | findstr name=").read()
        list = pattern.findall(out)
        component = list[0]

        return component
print getFocusedPackageAndActivity()



打印結果:com.android.settings/com.android.settings.Settings

如此就可以在使用monkeyrunner中的startActivity方法時調用該方法將獲取到的component傳入參數了!


發佈了26 篇原創文章 · 獲贊 5 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章