Android Interview Frequently Asked Questions - Handler Mechanism

Yesterday the interviewer asked whether multiple Handler objects can be created in a thread?

I thought I had a good understanding of the Handler mechanism, but I was still confused. I have never encountered such a situation in the project. First of all, the answer is yes, and multiple can be created. Next, I will explain the process of Handler sending messages:

First of all, it can be determined that there can only be a unique Looper and MessageQueue in each thread. The uniqueness is guaranteed by ThreadLocal. When the first Handler is initialized in a thread, it will be bound to the Looper and MessageQueue of the current thread ( Handler constructor It is written in this way: mLooper = Looper.myLooper(); mQueue = mLooper.mQueue(); ), and then when other Handlers are initialized, they will directly obtain the Looper and MessageQueue created when the first Handler is initialized.

Since the MessageQueue is one-to-many for the Handler, when the Handler queries the MessageQueue through the Looper to obtain the message, it first analyzes the parameters in the message, determines the Handler corresponding to the message, and then distributes it to the specified Handler for processing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324885829&siteId=291194637