Android MessageQueue

给你一囗甜甜゛ 提交于 2020-01-24 01:09:06

问题


We know main(UI) Thread is having implicit Looper attach with it so that its having 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?


回答1:


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();
}

Here is a related discussion.



来源:https://stackoverflow.com/questions/27704513/android-messagequeue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!