Search code examples
androidmultithreadinghandlerlooperandroid-looper

Sending messages from a different Handler to another handler's message queue


I want to send from another handler (not from the LooperThread mhandler itself) to the LooperThread 's message queue, but it does not show anything.

The thread.sleep is to initiate the mHandler.

Any ideas?

Main Activity

    new LooperThread().start();
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Handler handler = new Handler(LooperThread.mHandler.getLooper());

    handler.sendEmptyMessage(3);

LooperThread

class LooperThread extends Thread {
static  Handler mHandler;

public void run() {
    Looper.prepare();

    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d("LooperThread","handleMessage");
        }
    };

    Looper.loop();
}
}

Solution

  • The reason why you didn't see anything if because the message is sent to "handler" not "LooperThread.mHandler" but only "LooperThread.mHandler" prints something up.

    My suggestion is: - Use HandlerThread as suggested by @zapl and remove the sleep. getLooper will block when the looper is not ready. - Don't use static variable like "mHandler" and especially in this case you don't need "mHandler" at all to get the looper if you choose HandlerThread