Android 如何在ui线程上注入并等待注入完成后再继续?

Android 如何在ui线程上注入并等待注入完成后再继续?,android,junit,dependency-injection,dagger,Android,Junit,Dependency Injection,Dagger,在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)

在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);
        }
    }

问题是myRunnable在调用latch.await()时不会启动。运行JUnit时,使Dagger注入的最佳方法是什么?

您可以从AndroidTestCase使用此方法:

这一点也很有用: