• Preface
In the process of developing APP, we often need to update the UI;
But the UI thread of Android is not safe;
If you want to update the UI thread, it must be in the main thread of the process;
Here we refer to the asynchronous message processing mechanism to solve one of the problems.
• composition of asynchronous messages
concept
The asynchronous Message processing mechanism of Android is mainly composed of four parts: Message, Handler, MessageQueue and Looper.
Message
-
Message is a mechanism for transferring information between threads
- It can carry a small amount of information internally for exchanging data between threads.
-
Message can carry information with what, arg1, arg2 and obj.
- arg1 and arg2 are mainly used to carry integer data
- obj carries Object objects.
Handler
-
The Handler is the Handler of the message
- It is mainly used to send and process messages.
-
The sendMessage() method of Handle is used to send messages
-
When receiving a message, use Handler's handleMessage() to process the message
MessageQueue
-
MessageQueue means message queue
- It is mainly used to store all messages sent through the Handler
- This part of the message will be stored in MessageQeue until it is sent by Looper and processed by {handleMessage()
- There will only be one MessageQueue object per thread
Looper
-
Looper is the message manager of each MessageQueue
-
Loop's loop() method will enter an infinite loop
- Take out the message from MessageQueue and pass it to the handleMessage() method of Handle for processing
-
There will only be one Looper object per thread
Corresponding relationship between Thread,Looper and Handler
-
One Thread can only bind one Looper, but it can have multiple handlers
-
One Looper can bind multiple handlers
-
One Handler can only bind one Looper
• processing flow of asynchronous messages
Text description
Create a Handler object in the main thread and override the # handleMessage() method. We mainly carry out a series of operations in # handleMessage().
When UI update is needed in the sub thread, create a Message object msg in the sub thread and use the msg handler SendMessage (msg) sends this Message.
The message sent by the Handler will be added to the MessageQueue for processing;
Looper will always try to get messages from MessageQueue for processing.
Finally, Looper will send the message to the Handler's {handleMessage() method for processing.
Illustration
Next, we will further understand through the code;
Create an Empty Activity, which I name MainActivity2;
In activity_ main2. Add the following code to XML;
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="default" android:textSize="20sp" android:textColor="@color/black"/> </RelativeLayout>
In this layout, I only place a TextView control and initialize the text property to default;
Next, modify mainactivity2 Code in Java;
MainActivity2
public class MainActivity2 extends AppCompatActivity { private MyHandler handler; private TextView tv; //custom MyHandler Class, inherited from Handler Class and override handleMessage() method private class MyHandler extends Handler{ //By rewriting handlerMessage() method //To determine the update UI Operation of @Override public void handleMessage(@NonNull Message msg) { /* Perform different UI operations according to messages sent by different threads Identify different messages according to the what attribute of the Message object */switch(msg.what){ case 1: tv.setText("I'm a thread A"); break; case 2: tv.setText("I'm a thread B"); break; default: } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); tv = findViewById(R.id.tv); //Create in main thread Handler example handler = new MyHandler(); //By inheritance Thread Class implements multithreading new Thread(){ @Override public void run() { try { sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //Create the required message object Message msg = Message.obtain(); msg.what = 1;//Message ID msg.obj = "A";//Message memory storage //In the worker thread, through Handler Send message to message queue handler.sendMessage(msg); } }.start(); new Thread(){ @Override public void run() { try { sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } //Create the required message object Message msg = Message.obtain(); msg.what = 2;//Message ID msg.obj = "B";//Message memory storage //In the worker thread, through Handler Send message to message queue handler.sendMessage(msg); } }.start(); } }
code analysis
Create a MyHandler class by inheriting Handler, and rewrite the {handlerMessage() method;
In this method, by judging MSG Different operations are implemented for TextView according to what;
Create the Handler instance in the # onCreate() method, and create the child thread through # new Thread();
In the sub thread, create the Message object msg and use the Message handler SendMessage (msg) to send the intention of the sub thread to the main thread;
Finally, in the MyHandler class, handle different MSG through switch() what;
Operation effect
• declaration
reference material
[Asynchronous message processing mechanism]
[Android asynchronous communication: detailed explanation of the working principle of Handler mechanism [principle]