转载时请注明出处和作者联系方式
文章出处:http://www.limodev.cn/blog
作者联系方式:李先静 <xianjimli at hotmail dot com>
这几天做Broncho A1的Android兼容性测试(CTS),研究了一下Android的自动测试功能。它的执行流程如下:
1.用adb shell去启动测试程序,如:
adb shell am start -n com.google.android.contacts/.ContactsActivity
am是一个脚本命令:
# Script to start "am" on the device, which has a very rudimentary
# shell.
#
base=/system
export CLASSPATH=$base/framework/am.jar
exec app_process $base/bin com.android.commands.am.Am $*
不加任何参数运行am,我们可以看帮助信息:
[root@localhost ~]# adb shell am
usage: am [start|broadcast|instrument|profile]
am start -D INTENT
am broadcast INTENT
am instrument [-r] [-e ] [-p ]
[-w]
am profile [start |stop]
INTENT is described with:
[-a ] [-d ] [-t ]
[-c [-c ] ...]
[-e|--es ...]
[--ez ...]
[-e|--ei ...]
[-n ] [-f ] []
am 是在命令行启动android程序的一种方法,它是在cmds/am/src/com/android/commands/am/Am.java里实现的。
在函数runInstrument实现了instrument 命令,主要做了下面的事:
1.参数解析
2.创建一个InstrumentationWatcher对象,用来接收测试结果。
3.调用IActivityManager的startInstrumentation运行测试程序。
4.调用InstrumentationWatcher的waitForFinish函数等待测试结束。
private void runInstrument() {
...
try {
if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) {
System.out.println("INSTRUMENTATION_FAILED: " +
cn.flattenToString());
showUsage();
return;
}
} catch (RemoteException e) {
}
...
if (watcher != null) {
if (!watcher.waitForFinish()) {
System.out.println("INSTRUMENTATION_ABORTED: System has crashed.");
}
}
...
}
startInstrumentation实际上是在services/java/com/android/server/am/ActivityManagerService.java里执行的,执行过程如下:
1.调用PackageManager的getInstrumentationInfo获取InstrumentationInfo和ApplicationInfo。
2.uninstall原来的测试程序(如果前面运行了相同的测试程序,就会停止它)
3.运行新的测试程序。
public boolean startInstrumentation(ComponentName className,
String profileFile, int flags, Bundle arguments,
IInstrumentationWatcher watcher) {
...
try {
ii = mContext.getPackageManager().getInstrumentationInfo(
className, 0);
ai = mContext.getPackageManager().getApplicationInfo(
ii.targetPackage, PackageManager.GET_SHARED_LIBRARY_FILES);
} catch (PackageManager.NameNotFoundException e) {
...
uninstallPackageLocked(ii.targetPackage, -1, true);
ProcessRecord app = addAppLocked(ai);
...
}