[英]How to inject on the ui-thread and wait for the injection to finish before continue?
在Dagger中,您必须注入UI线程。 运行JUnit时,您不在UI线程上运行。 为了使其工作,我们必须在UI线程上发布一个Runnable并等待其完成注入。
我的代码如下所示:
public void inject(final Object object) {
// We always has to inject on the main thread.
final CountDownLatch latch = new CountDownLatch(1);
Handler mainHandler = new Handler(FodoApplication.getAppContext().getMainLooper());
Runnable myRunnable = new Runnable() {
public void run() {
objectGraph.inject(object);
latch.countDown();
}
};
mainHandler.post(myRunnable);
try {
latch.await();
} catch (InterruptedException e) {
Log.e(TAG, "", e);
}
}
问题在于,当调用latch.await()时,myRunnable无法启动。 在运行JUnit时,使Dagger注入的最佳方法是什么?
您可以从AndroidTestCase使用此方法: http : //developer.android.com/reference/android/app/Instrumentation.html#runOnMainSync (java.lang.Runnable )
这个也很有用: http : //developer.android.com/reference/android/test/InstrumentationTestCase.html#runTestOnUiThread(java.lang.Runnable)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.