Handler and handler

Source: Internet
Author: User

Handler and handler

This section describes how to use Handler and related knowledge. Before learning about Handler, let's take a look at these questions.

  • What is Handler?
  • There are several typical methods for updating the UI of a sub-thread. What are these methods essentially?
  • Does the subthread really fail to update the UI?
  • What is HandlerThread?
  • How do the main thread and subthreads communicate with each other?

Well, if the above question is correct, and you know the principle, there is no need to continue reading it. Otherwise, you should make up (^ o ^ )/~.

What is Handler?

Handler is a mechanism provided by Android to update the UI and a message processing mechanism. We can send messages or process messages through Towers, handler is very common in our framework.

After reading the above explanation, we have a question: why is Handler used?

Android encapsulates a set of message creation, transmission, and processing mechanisms during design. If this mechanism is not followed, there is no way to update the UI information, and an exception is thrown;

Next, let's take a look at how Google encapsulates such a Handler mechanism in the thread from the source code perspective. Let's first look at the Main method of the Java entry function.


In android. app. ActivityThread. java.

Next we will focus on the three lines of code L4 L10 L20.

L4:

Then look at L88 and L93.

The code above shows that a logoff instance is initialized from the very beginning, and then the instance is saved in the sThreadLocal member variable. Then, the myLoop () method is called as needed, then, retrieve the loose instance. So it is easy to get,A thread corresponds to a unique logoff instance

L10:
Check the 10th lines of code.sMainThreadHandler = thread.getHandler();Before that, let's take a look at the 6th lines of code.
ActivityThread thread = new ActivityThread();
Then let's take a look at the member variables of the ActivityThread class:

Line 3 shows a very strange Class H, member variable.final H mH = new H();
Next let's take a look at the most streamlined class:

See the lifecycle of the Activity we are familiar with. Right, the lifecycle of the Activity is triggered here, so the initial L10sMainThreadHandler = thread.getHandler();The retrieved Handler instance is such an H-class instance.

final Handler getHandler() {        return mH;}

L20:

The above code first obtains the logoff instance, and then obtainsMessageQueueAnd then traverse the queue in an endless loop.

Now, the Logoff of the UI thread is ready.

There are several typical methods for updating the UI of a sub-thread. What are these methods essentially?

Since Google has prepared a Handler mechanism for us, it is very easy to interact with the main thread in the sub-thread. What other methods can be used to interact with the UI thread through the Handler, what are these interaction methods in essence? Let's look at them together.

From the sdks provided by Google, we probably know the following methods:

Let's take a look at the Demo of the above four interactive methods:



Here is a special supplement to the L24 Method for adding the parent class constructor:

public UpdateViewHandler(TextView textView){    super();    this.textView = new WeakReference<>(textView);}

The code above is written by introducing Lambda expressions in Java. The code is relatively simple. I will not describe it here. What we will be interested in next is that the source code of the above four interactive methods is like a magic horse?

  • Let's first look at the first method of updateViewByHandlerPost.

The above code must note L37 linesmsg.target = this;This line of code indicates that Handler has to have a receiver to send messages, and the receiver is itself (the Handler instance itself ).

  • Next, let's take a look at updateViewByHandlerMessage.

Note that the above Code is L3. The Message instance here has two methods:
Message message = Message.obtain();AndMessage message = new Message();Which of the two methods is better or no difference? Why, think for yourself.

  • Next, let's take a look at updateViewByRunOnUiThread.

If it is not in the UI thread, call the post of Handler.

  • Finally, let's look at updateViewByViewPost.

The post of Handler is still called. Therefore, the above four methods basically call the communication mechanism of Handler. Therefore, the Android sub-thread updates the UI through the Handler mechanism in essence.

Does the sub-thread really fail to update the UI?

Through the above four methods of updating the UI through the sub-thread, we basically understand the Android Handler mechanism, but does the sub-thread really cannot update the UI? Let's make a test.

After the operation, my friends were stunned and the operation was perfect. What is the situation of Shenma?

We will not answer this question directly, but implement it in another way:

After this operation, will it immediately Crash? And throwOnly the original thread that created a view hierarchy can touch its views.Exception. What is the situation of Shenma?

To answer this question, you still need to returnActvityThreadFind the answer in this class. The specific details are not described here. Let's give the reason directly. The ViewParent has not been initialized during the onCreate lifecycle, this will cause re-painting when updating the UI on The View. Let's take a look at the Code:

Note L16 lines,pIt is null, so it will not be executedp.invalidateChild(this, damage);Method
Let's see what this method is.


Check if you see the exception that you are familiar with. Check whether the preceding strange events are located here. The main reason is that ViewParent is not initialized, so the UI Thread Check is not executed. If the initialization is complete, check the update operation of the UI thread. At this time, any sub-thread attempts to update the UI is invisible.

What is HandlerThread?

All of the above are the sub-threads that actively communicate with the UI thread, but the cool and cool UI thread never actively say hello to the sub-thread. Is it too rude, then how does the main thread greet the sub-thread? Here, Google provides HandlerThread, which is used to facilitate the communication between the UI thread and the sub-thread. Can we leave this class alone and start it on our own, let's try it out without HandlerThread.



The idea of the Code is wrong. The main thread communicates with the sub-thread first, and then communicates with the main thread after the sub-thread has a result. This logic is correct, however, when we run the program, the system prompts that there is a null pointer exception in L66. This problem is not caused by multithreading. Because the logoff has not been initialized yet, a null pointer exception is reported, the HandlerThread provided by Google is synchronized. Therefore, if we replace the sub-thread with a loose as HandlerThread, there will be no problem caused by this multi-thread concurrency.

How to communicate with each other between the main thread and sub-Thread

The above has basically answered how the main Thread and sub-Thread communicate with each other. HandlerThread is generally recommended. If you are not willing to use it directly, you can also define a Thread with logoff, however, the multi-thread concurrency issue must be well handled. In addition, for the Handler constructor, one of the parameters is Callback. What is the function of this Callback? Let's take a look at the source code. Everything is clear.

Obviously, if this callback returns true, it will not continue to be executed, so this callback has the function of intercepting.

The introduction of Handler is basically over. Of course, there is still a lot of other Handler knowledge. I will not repeat it here.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.