简体   繁体   English

将消息从其他处理程序发送到另一个处理程序的消息队列

[英]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. 我想从另一个处理程序(而不是从LooperThread mhandler本身)发送到LooperThread的消息队列,但是它什么都不显示。

The thread.sleep is to initiate the mHandler. thread.sleep用于启动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 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();
}
}

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. 之所以没有看到任何内容的原因是因为消息发送到“处理程序”而不是“ LooperThread.mHandler”,而是仅“ LooperThread.mHandler”打印了一些内容。

My suggestion is: - Use HandlerThread as suggested by @zapl and remove the sleep. 我的建议是:-使用@zapl建议的HandlerThread并删除睡眠。 getLooper will block when the looper is not ready. 当循环程序尚未准备就绪时,getLooper将阻塞。 - 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 -不要使用“ mHandler”之类的静态变量,尤其是在这种情况下,如果您选择HandlerThread,则根本不需要“ mHandler”来获得循环器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM