移动测试基础 通过 adb shell dumpsys 命令获取当前应用的 component

xuxu · 2014年06月22日 · 最后由 securitytest 回复于 2017年09月26日 · 3124 次阅读
本帖已被设为精华帖!

在一些 Q 群里面经常会有同学问如何获取应用程序的包名和入口 Activity,就是 am start 命令里面和 monkeyrunner startActivity 方法中的 component 参数,周末在家总结了下获取的几个方法,有写在博客上,还没在 TesterHome 上发过贴,就把内容搬过来发一遍,博客地址:http://blog.csdn.net/gb112211/article/details/33073191
原文:
在 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 传入参数了!

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 7 条回复 时间 点赞

不错, 前几天另外一个帖子也讨论了很多方法。都很不错

收藏了, 哈哈

借鉴借鉴

收藏了哈

超赞,xuxu 写的很不错,不过我没有采用 python 的形式,我用的是 Windows,直接写了个 bat 文件
命令如下:
adb shell dumpsys window w | findstr \/ | findstr name= > appinfo.txt
appinfo.txt
结果如下:
mSurface=Surface(name=com.miui.home/com.miui.home.launcher.Launcher)
我这样写的用处是,哪个页面发生了 bug,提 bug 时直接把页面贴上去,省了开发翻页面的时间,直接定位到相应的 Activity

每次都要执行一次 shell 命令效率实在很低啊,不过目前还真没有太好的办法

需要 登录 後方可回應,如果你還沒有帳號按這裡 注册