instrumentation原理

1.官方描述

instrumentation can load both a test package and the application under test into the same process. Since the application components and their tests are in the same process, the tests can invoke methods in the components, and modify and examine fields in the components.

翻译过来

Instrumentation可以把测试包和目标测试应用加载到同一个进程中运行。既然各个控件和测试代码都运行在同一个进程中了,测试代码当然就可以调用这些控件的方法了,同时修改和验证这些控件的一些数据

2.如何实现获取控件及操作控件

Android instrumentation是Android系统里面的一套控制方法或者”钩子“。这些钩子可以在正常的生命周期(正常是由操作系统控制的)之外控制Android控件的运行,其实指的就是Instrumentation类提供的各种流程控制方法,下表展示了部分方法的对应关系

Method Control by User(Instrumentation) Control by OS
onCreate callActivityOnCreate onCreate
onDestroy callActivityOnDestroy onDestroy
onStart callActivityOnStart onStart

具体源码:

/**     * Perform calling of an activity's {@link Activity#onCreate}     * method.  The default implementation simply calls through to that method.     *      * @param activity The activity being created.     * @param icicle The previously frozen state (or null) to pass through to     *               onCreate().     */    public void callActivityOnCreate(Activity activity, Bundle icicle) {        ...        activity.performCreate(icicle);        ...}

从代码可以看到它做的事情也就是直接调用Activity类的performCreate方法:

final void performCreate(Bundle icicle) {        onCreate(icicle);        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(                com.android.internal.R.styleable.Window_windowNoDisplay, false);         ...        

而performCreate方法最终调用的就是onCreate方法。所以这里就好比Instrumentation勾住了本应该系统调用的onCreate方法,然后由用户自己来控制勾住的这个方法什么时候执行。

获取Activity中的控件

public void testActivity() throws Exception {          Intent intent = new Intent();        intent.setClassName("com.hustophone.sample", Sample.class.getName());        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        activity = (Activity) getInstrumentation().startActivitySync(intent);        text = (TextView) activity.findViewById(R.id.text1);        button = (Button) activity.findViewById(R.id.button1);

操作Activity中的控件

    getInstrumentation().runOnMainSync(new PerformClick(button));    ...    /*     * 模拟按钮点击     */    private class PerformClick implements Runnable {        Button btn;        public PerformClick(Button button) {            btn = button;        }        public void run() {            btn.performClick();        }    }

更多相关文章

  1. Android控件显示与隐藏
  2. Starting an Activity(开始活动)
  3. Android编译出错:app:checkDebugDuplicateClasses
  4. Android: ViewDragHelper tutorial
  5. 仿照DatePickerFragment实现的TimePickerFragment
  6. 探索FragmentTransaction#commit()抛出IllegalStateException
  7. Android学习笔记-Android初级 (二)
  8. Android(安卓)Retrofit2网路编程实现方法详解
  9. Android存储登陆信息

随机推荐

  1. Android九宫格抽奖
  2. android p vts VtsTrebleVendorVintfTest
  3. Android Tips
  4. maven 工程转换成 gradle 工程
  5. android 颜色对应值
  6. Android在标准linux基础上对休眠唤醒的实
  7. Android下载(外文)
  8. Android ViewPager的简单使用
  9. Android Studio build.gradle 编码配置UT
  10. Ubuntu 及windows 环境下android(Launcher