Interview questions related to asynchronous message processing mechanism - detailed explanation of handler interview questions

What is a handler?

 This exception should also be the reason for the handler, that is, by default, it is impossible to update the UI in the non-UI thread, so what is the handler?

The handler associates the corresponding thread's MessageQueue by sending and processing Message and Runnable objects.

1. The corresponding Message and Runnable can be processed accordingly at a certain point in the future.

2. Put the time-consuming operations you want to process on the sub-thread, and let the operation of updating the UI be on the main thread.

How to use handler:

  • post(runnable)
    check the code. In fact, it also calls sendMessage(), as follows:
  • sendMessage(message)

The principle of handler mechanism:

Let's take a look at the picture first:

From the perspective of source code, let's first look at the constructor of handler() to create a looper:

Then also create a MessageQueue:

It can be found that MessageQueue is created in Looper, so how is Looper created?

It is obtained through ThreadLocal, that is, different threads obtain their own Looper. When will the Looper object be placed in ThreadLocal?

At this time, the Handler holds the MessageQueue, and the MessageQueue is created in the Looper, so that the three are organically related.

Then Looper needs to call the loop() method to get messages from MessageQueue and process them. See the source code for details:

And what is the targetget in msg.target?

Oh~~ it turns out to be Handler, then let's take a look at its dispatchMessage() method:

And methods like Msg.obtain() are in the form of callback. So far, the entire handler message processing process has been completely analyzed. Let’s review it with a diagram:

Memory leaks caused by handler and solutions:

 

Solution:

1. The handler can be declared as a static inner class, as follows:

②, you can also call the following method in onDestroy() in Activity:

3. Let the handler internally hold a weak reference to the external Activity.

Guess you like

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