A deep understanding of the message mechanism Handler in android

Source: Internet
Author: User
Tags echo message

A deep understanding of the message mechanism Handler in android

What is Handler?
Handler is a set of mechanisms provided by Android to update the UI and a set of message processing mechanisms.
We can use it to send messages or process messages.

Why should we use Handler?
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 and exception information will be thrown.

For example, we all know that the operations to update the UI are generally put in the main thread. When we need to update the UI in the Child thread, we need to use Handler, although there are several methods to update the Ui in the sub-thread, the internal implementation principle is basically to send message processing through Handler. Don't worry, as mentioned below.

Handler usage:

Use of the sendMessage () method:
Package com. hnthgys. mytext; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. support. v7.app. appCompatActivity; import android. widget. textView; public class MainActivity extends AppCompatActivity {private TextView TV; // create the main thread's Handler private Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {super. handleMessage (msg); TV. setText ("I sent a message update via handler") ;};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); TV = (TextView) findViewById (R. id. textview); // enable the subthread new Thread () {@ Override public void run () {super. run (); // For example, here we are executing a time-consuming operation. After the operation is completed, send the message update ui // send an empty message handler. sendEmptyMessage (0); // if we need to use the time-consuming data, we can write // Message msg = handler. obtainMessage (); // msg. obj = "data"; // handler. sendMessage (msg );}}. start ();}}

SendEmptyMessage (); this method is consistent with sendMessage. The difference is to send an empty message.

SendMessageDelayed (); sends a delayed message.

Post (Runnable); this method can update the UI in the Child thread. This method runs in the main thread.

RemoveCallbacksAndMessages (); remove the echo message. For example, you can use this method to stop the Handler carousel when we want it to play images.

Why does android only use handler to update the UI?

The most fundamental goal is to solve the problem of multi-thread concurrency. If there are multiple threads in an activity to update the UI without locking, what will happen? An error occurred while updating the interface.

You may say that I can use multi-thread locking. If I lock all UI update operations, the performance of the application will be greatly reduced.
Considering the above issues, Android provides us with a set of UI update mechanisms. We only need to follow this mechanism.
There is no need to worry about multithreading at all, so the UI update operations are all round-robin in the message queue of the main thread.

What is the principle of Handler?
1. Handler encapsulates the sending of a message (including WHO the message is sent)
Loler (Looper of Handler)
1. contains a message queue (MessageQueue). All Handler send messages.
All go to this message queue.
2. The logoff. loop () method is an endless loop that constantly retrieves messages from MessageQueue,
If a message exists, the message is processed and blocked if no message exists.

2. MessageQueue is a message queue that can add and process messages.

3. Handler, Which is internally associated with Lopper, that is, the Handler's
You can find the loader internally and find the MessageQueue after finding the Lopper,
In Handler, messages are actually sent to the MessageQueue queue.

Handler principle summary:
Handler is responsible for sending messages, and Loooper is responsible for receiving messages sent by Handler,
And directly send the message back to Handler.
MessageQueue is a container for storing messages.

Handler problems:
An exception thrown when updating the UI in a non-UI thread:

The exception thrown when Handler is created in the sub-thread:

Note:To create a Handler in a child thread, you must first create a logoff because there is no logoff object in the Child thread.

What is HandlerThread?

When we create a thread-related Handler, we can use HandlerThread to solve the thread-related concurrency problem.

How to send messages to each other between the subthread and the main thread:

The main thread Handler sends messages to the subthread (pseudocode)
The sub-thread Handler sends messages to the main thread (pseudocode)

Android updates the UI in sub-thread:
Use pictures. The previous notes seem clearer ..

Does a non-UI thread really fail to update the UI?
The answer is yes. You are not mistaken, And the UI can be updated by non-UI threads. You may think that I am talking about it. Let's look at the code below:

Package com. hnthgys. mytext; import android. OS. bundle; import android. OS. handler; import android. support. v7.app. appCompatActivity; import android. widget. textView; public class MainActivity extends AppCompatActivity {private TextView TV; // create the main thread's Handler private Handler handler = new Handler (); @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); TV = (TextView) findViewById (R. id. textview); // enable the subthread new Thread () {@ Override public void run () {super. run (); // SystemClock. sleep (100); TV. setText ("I am updating the UI in the Child thread ");}}. start ();}}

I also posted the layout code,


  
      
   
  

Run:

You may have been stunned. How is it possible, fuck? It's totally revolutionary .....

Main reasons:
When we update the UI, The checkThread () method in the ViewRootImpl class in Android will check the thread where the UI is currently updated,

3937 void More... checkThread () {// check the thread where the UI is updated 3938 if (mThread! = Thread. currentThread () {// if it is not in the UI thread, the following exception will be thrown, you should be familiar with it. 3939 throw new CalledFromWrongThreadException (3940 "Only the original thread that created a view hierarchy can touch its views. "); 3941} 3942}

After checking the system source code, you will find that the ViewRootImpl class will be initialized only after the onResume () method of the Activity is executed. This explains the reason why the above Code can run. However, no, we didn't perform any time-consuming operations in the Child thread. If I add this code in the Child thread:

SystemClock.sleep(100);

Then the system will throw an exception: "Only the original thread that created a view hierarchy can touch its views ."
You cannot update the UI in a non-UI thread.
The problem arises. If the ViewRootImpl class is not initialized, how does the view display it ??? I am working on it .......

In addition, when we get ViewRoot in the Child thread, we can call addView () method to update the UI in the Child thread. The details here are explored by everyone .....

Related Article

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.