HandlerThread th1 = new HandlerThread("HandlerThreadTest") {
protected void onLooperPrepared() {
mDidSetup = true;
mLooperTid = Process.myTid();
}
};
assertFalse(th1.isAlive());
assertNull(th1.getLooper());
th1.start();
assertTrue(th1.isAlive());
assertNotNull(th1.getLooper());
/*
* Since getLooper() will block until the HandlerThread is setup, we are guaranteed
* that mDidSetup and mLooperTid will have been initalized. If they have not, then
* this test should fail
*/
// Make sure that the onLooperPrepared() was called on a different thread.
assertNotSame(Process.myTid(), mLooperTid);
assertTrue(mDidSetup);
final Handler h1 = new Handler(th1.getLooper()) {
public void handleMessage(Message msg) {
assertEquals(TEST_WHAT, msg.what);
// Ensure that we are running on the same thread in which the looper was setup on.
assertEquals(mLooperTid, Process.myTid());
mGotMessageWhat = msg.what;
mGotMessage = true;
synchronized(this) {
notifyAll();
}
}
};
Message msg = h1.obtainMessage(TEST_WHAT);
synchronized (h1) {
// wait until we have the lock before sending the message.
h1.sendMessage(msg);
try {
// wait for the message to be handled
h1.wait();
} catch (InterruptedException e) {
}
}
assertTrue(mGotMessage);
assertEquals(TEST_WHAT, mGotMessageWhat);