FileDocCategorySizeDatePackage
HandlerThreadTest.javaAPI DocAndroid 5.1 API3518Thu Mar 12 22:22:12 GMT 2015android.os

HandlerThreadTest

public class HandlerThreadTest extends TestCase

Fields Summary
private static final int
TEST_WHAT
private boolean
mGotMessage
private int
mGotMessageWhat
private volatile boolean
mDidSetup
private volatile int
mLooperTid
Constructors Summary
Methods Summary
public voidtestHandlerThread()

    
    
         
        HandlerThread th1 =  new HandlerThread("HandlerThreadTest") {
            protected void onLooperPrepared() {
                synchronized (HandlerThreadTest.this) {
                    mDidSetup = true;
                    mLooperTid = Process.myTid();
                    HandlerThreadTest.this.notify();
                }
            }
        };
        
        assertFalse(th1.isAlive());
        assertNull(th1.getLooper());
        
        th1.start();
        
        assertTrue(th1.isAlive());
        assertNotNull(th1.getLooper());
       
        // The call to getLooper() internally blocks until the looper is
        // available, but will call onLooperPrepared() after that.  So we
        // need to block here to wait for our onLooperPrepared() to complete
        // and fill in the values we expect.
        synchronized (this) {
            while (!mDidSetup) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        
        // Make sure that the process was set.
        assertNotSame(-1, mLooperTid);
        // Make sure that the onLooperPrepared() was called on a different thread.
        assertNotSame(Process.myTid(), mLooperTid);
        
        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);