对于Web网页来说,页面的访问、加载速度对于用户体验来说是很重要的,而如果把Android中的每个Activity都看成是一个页面的话,Activity的启动速度凭主观的话是较难精确衡量的,因此如果可以测试每个Activity的启动速度或者获得其它基本指标并进行日常监测那就更好了。
一、编写继承于Instrumentation类的LaunchPerformanceBase类
/** * Base class for all launch performance Instrumentation classes. */ public class LaunchPerformanceBase extends Instrumentation { public static final String TAG = "LaunchPerformanceBase"; protected Bundle mResults; protected Intent mIntent; /** * Constructor. */ public LaunchPerformanceBase() { mResults = new Bundle(); mIntent = new Intent(Intent.ACTION_MAIN); mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); setAutomaticPerformanceSnapshots(); } /** * Launches intent {@link #mIntent}, and waits for idle before * returning. */ protected void LaunchApp() { startActivitySync(mIntent); waitForIdleSync(); } @Override public void finish(int resultCode, Bundle results) { super.finish(resultCode, results); } } |
在这个类的构造函数中setAutomaticPerformanceSnapshots()为Instrumentation设置为开启性能快照功能。
LaunchApp()方法中用于启动相应的Activity, waitForIdleSync()方法则为等待Activity空闲时,即等待Activity启动完毕。
二、编写ActivityLaunchPerformanceTest类
public class ActivityLaunchPerformanceTest extends LaunchPerformanceBase { /** * Outfile argument name. * This argument can be passed to the instrumentation using <code>-e</code>. */ private static final String launchActivityName = "launch_activity"; /** * Output file name. */ private String classNameForIntent; private String DEFAULT_ACTIVITY = "SplashActivity"; /** * Constructor. */ public ActivityLaunchPerformanceTest() { super(); } @Override public void onCreate(Bundle arguments) { if ( arguments != null ) { classNameForIntent = arguments.getString(launchActivityName); } if ( classNameForIntent == null ) { classNameForIntent = DEFAULT_ACTIVITY ; } super.onCreate(arguments); mIntent.setClassName("com.company.example", "com.company.example.ui.activity." + classNameForIntent); start(); } /** * Calls LaunchApp and finish. */ @Override public void onStart() { super.onStart(); LaunchApp(); finish(Activity.RESULT_OK, mResults); } } |
这个类中onCreate()方法中传入要测试的Activity的名字。