user2808671
user2808671

Reputation: 271

Why does Handler.Post Block the main Thread

This is a class which extends Thread and implements the run() function:

public class TestThread extends Thread{
public Handler handler;
public TestThread(){

    handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
        }
    };
}
public Looper getLooper(){
    return Looper.myLooper();
}
@Override
public void run() {
    // TODO Auto-generated method stub
        Looper.prepare();
        Looper.loop();      
}
}

Now in a button in the main activity I have this code:

TestThread t=new TestThread();
    t.start();  
    Handler h=new Handler(t.getLooper());
    h.post(new Runnable(){
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true);
        }
    });

As far as I know this is supposed to put the runnable in the target Thread's message queue and the thread (not UI thread) will run it when possible. But this code blocks the UI. why does this happen? As you see I sent the target thread's looper to the Handler constructor and the handler should use that looper not the main thread's looper.

Upvotes: 0

Views: 1567

Answers (1)

laalto
laalto

Reputation: 152797

Looper.myLooper() returns the current thread looper which is the calling UI thread's looper for you. Then you make a handler with it and post a blocking runnable there.

To make this "work", move the myLooper() call under the thread run() method.

Upvotes: 2

Related Questions