问题
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