问题描述
我编写了一个Android工具测试,该测试会调用我的服务并通过广播接收答案.
I have written an Android instrumentation test that calls my service and receives an answer via an broadcast.
与服务对话的要测试的代码使用处理程序.
The code to be tested, which speaks to the service, uses handler.
在测试我的测试过程中,^^我注意到处理程序的行为不符合预期.因此,我编写了一个测试来检查这种行为:
In process of testing my test ^^ I noticed that the handlers are not behaving as expected. So I've written an test to check on this behaviour:
import android.os.Handler;
import android.support.test.annotation.UiThreadTest;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@RunWith(AndroidJUnit4.class)
public class HandlerTest {
private CountDownLatch countDownLatch;
@Test
@UiThreadTest
public void handlerTest() {
final Handler handler = new Handler();
countDownLatch = new CountDownLatch(1);
final Runnable r = new Runnable() {
@Override
public void run() {
// this code gets not executed
countDownLatch.countDown();
}
};
handler.postDelayed(r, 1000);
try {
final boolean finishedWithoutTimeout
= countDownLatch.await(5, TimeUnit.SECONDS);
Assert.assertTrue(finishedWithoutTimeout);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
处理程序不执行可运行的代码.这也是我的生产代码的问题.
The handler dosn't execute the runnable code. This is also the problem with my production code.
我用 @UiThreadTest
批注修复的 Looper.prepare()
问题.
关于我的处理程序问题有什么建议吗?
Are there any suggestions regarding my handler problem?
推荐答案
原因是您在此处锁定了 thread
:
The reason is that you locked your thread
here:
final boolean finishedWithoutTimeout = countDownLatch.await(5, TimeUnit.SECONDS);
并且当 thread
被锁定时,您不能使用 handler
发送 ranable
. Thread
刚刚被锁定.您可以通过将您的 handler
链接到另一个 thread
来解决此问题.这是通过 handlerThread
的简单解决方案:
And when the thread
is locked, you can't send a rannable
with your handler
. The Thread
is just locked.You can solve it by linking your handler
to another thread
. Here is a simple solution via handlerThread
:
@Test
@UiThreadTest
public void handlerTest() {
countDownLatch = new CountDownLatch(1);
final HandlerThread handlerThread = new HandlerThread("solution!");
handlerThread.start();
final Runnable r = new Runnable() {
@Override
public void run() {
countDownLatch.countDown();
}
};
Handler handler = new Handler(handlerThread.getLooper());
handler.postDelayed(r, 1000);
try {
final boolean finishedWithoutTimeout = countDownLatch.await(5, TimeUnit.SECONDS);
Assert.assertTrue(finishedWithoutTimeout);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
这篇关于处理程序未在Instrumental Test中执行Runnable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!