1

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();
}
}
Nick
  • 2,818
  • 5
  • 42
  • 60
  • no idea but you can use the supplied `HandlerThread` class like `HandlerThread ht = new HandlerThread("MyHandlerThread"); ht.start(); Handler h = new Handler(ht.getLooper()) { .. handleMessage ... }; h.send..` which saves you from a lot of problems like having to wait for long and ANR your app – zapl Aug 07 '18 at 22:02
  • @zapl I know all about HandlerThread class. What iam asking is... How can i send message from a different handler to LooperThread's message queue? – Nick Aug 08 '18 at 08:38
  • 1
    `LooperThread.mHandler.sendEmptyMessage(3);` will send a message to the Handler you expect. Your code sends it instead to a different Handler that uses the same looper though - (the queue of your looper thread is shared between those handlers and the looper delivers the message to the right handler) – zapl Aug 08 '18 at 14:42

1 Answers1

0

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

zulutime
  • 101
  • 4
  • I know all about HandlerThread class. What iam asking is... How can i send message from a different handler to LooperThread's message queue? – Nick Aug 08 '18 at 08:37
  • 1
    You have 2 "Handler" attached to the same MessageQueue/Looper. And every message has its destination set to the handler it's created from. So if you want "mHandler" to handle message, you need to get a hold of "mHandler" and send message via it – zulutime Aug 08 '18 at 18:07