本文介绍了Android MessageQueue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道main(UI)线程正在与隐式Looper相连,以便其具有MessageQueue.

We know main(UI) Thread is having implicit Looper attach with it so that its having MessageQueue.

我们还知道,可以在Looper.prepare()的帮助下将MessageQueue附加到工作线程上

And we also know that we can attach MessageQueue to worker thread with the help of Looper.prepare()

我的问题是两个队列都相同吗?

My question is that is it both Queue are same?

推荐答案

MessageQueue不同,当您在新线程中调用Looper.loop()时,新的MessageQueue将附加到新创建的线程上.然后我们通常使用Handler与线程通信.应用启动时,系统会创建主UI线程的MessageQueue.您可以通过它们的引用来比较消息队列.

It's not the same MessageQueue, when you call Looper.loop() in a new thread, a new MessageQueue will attache to the new created thread. Then we usually use Handler to communicate with the thread. The main UI thread's MessageQueue is created by system when you app start. You can compare the message queues by their reference.

private static final String TAG = MainActivity.class.getSimpleName();
private Handler mHandler;
private MessageQueue messageQueue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    messageQueue = Looper.myQueue();
    new Thread() {

        @Override
        public void run() {
            super.run();
            Looper.prepare();
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (Looper.myQueue().equals(messageQueue)) {
                        Log.d(TAG, "same message queue");
                    } else {
                        Log.d(TAG, "not the same queue");
                    }
                }
            };
            mHandler.sendEmptyMessage(0);
            Looper.loop();
        }
    }.start();
}

此处是一个相关讨论.

这篇关于Android MessageQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 17:55