如果,我们需要新建一个线程,并且这个线程要能够循环处理其他线程发来的消息事件,或者需要长期与其他线程进行复杂的交互,这时就需要用到Looper来给线程建立消息队列。
建立好消息队列后往下的重点就是调用AndroidTestRunner的runTest方法开始测试用例的执行了:
public void runTest(TestResult testResult) {
mTestResult = testResult;
for (TestListener testListener : mTestListeners) {
mTestResult.addListener(testListener);
}
Context testContext = mInstrumentation == null ? mContext : mInstrumentation.getContext();
for (TestCase testCase : mTestCases) {
setContextIfAndroidTestCase(testCase, mContext, testContext);
setInstrumentationIfInstrumentationTestCase(testCase, mInstrumentation);
setPerformanceWriterIfPerformanceCollectorTestCase(testCase, mPerfWriter);
testCase.run(mTestResult);
}
}大概做法就是对所有收集到的测试集进行一个for循环然后取出每个测试用例在junit.Framework.Testcase环境下进行运行了。这里就不往下研究junit框架是怎么回事了。总结以上的分析,android.test.InstrumentationTestRunner会在目标应用代码运行之前调用onCreate方法来建立一个新的线程并准备后消息队列,然后会开始基于Instrumentation的测试集的测试。
既然app的主线程和instrumetnaiton测试用例脚本线程是运行在同一个进程中的,我们脑袋中应该就会立刻闪现以下有关UiThread和子线程的两点限制:
子线程是可以直接获取主线程UiThread的控件以及内容的
子线程是不能直接操作主线程UiThread的控件以及内容的
根据网上的文章《Android中UI线程与后台线程交互设计的5种方法》的描述,android提供了以下几种方法,用于实现后台线程与UI线程的交互。
1、handler
2、Activity.runOnUIThread(Runnable)
3、View.Post(Runnable)
4、View.PostDelayed(Runnabe,long)
5、AsyncTask
而Instrumentation类又提供了一个runOnMainSync的方法,这和上面的Activity提供的runOnUiThread方法从名字上比较接近,那么我们这里就对比下这两种方法有什么区别。我们先看下Activity的runOnUIThread方法:
/**
* Runs the specified action on the UI thread. If the current thread is the UI
* thread, then the action is executed immediately. If the current thread is
* not the UI thread, the action is posted to the event queue of the UI thread.
*
* @param action the action to run on the UI thread
*/
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}其代码的功能和对应的描述一致:
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/ruanjian/article-26961-5.html
现在是剩女多好吧
光看数量就行了