Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Asynchronous message Mechanism in Android

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "how to realize the asynchronous message mechanism in Android", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve asynchronous message mechanism in Android" article.

The asynchronous messaging mechanism in Android is divided into four parts: Message, Handler, MessageQueue, and Looper.

Where Message is a message passed between threads, its what, arg1, and arg2 fields can carry integer data, and the obj field can carry an Object object.

Handler is the processor and is mainly used to send and process messages. The way to send a message is that sendMessage; processes the message as handleMessage (), and the information carried by the Message field is used as a discrimination in this method.

MessageQueue is a message queue that holds all messages sent by Handler.

Looper is the "housekeeper" of the message queue, taking messages out of the message queue one by one and dispatching them to the handleMessage () method of Handler.

The flow of asynchronous message processing is:

① first, you need to create a Handler object in the main thread and override the handleMessage () method.

② when a child thread finishes processing a time-consuming operation and needs to feed back the processing result to UI, first create a Message object and have its what field carry an int value, and then send it out through the Handler object.

After the ③, the message is added to the MessageQueue waiting to be processed, while the Looper always tries to fetch the pending message from the MessageQueue and finally distribute it back to the handleMessage () method in the Handler object. Because the Handler object is created in the main thread, you can safely perform the UI operation in the handleMessage () method.

Verify this with an example: there is a button and a TextView in the active MainActivity. TextView initializes the display of "Hello World!", then clicks the button to perform a time-consuming operation; when the time-consuming operation is over, TextView displays "Nice to meet you". Based on the above analysis, I wrote the following code very naturally:

Package com.shaking.androidthreadtest;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private static final int UPDATE_TEXT=1; private String data; private TextView textView; private Handler handler=new Handler () {@ Override public void handleMessage (Message msg) {switch (msg.what) {case UPDATE_TEXT: textView.setText (data) }; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.main_layout); Button button=findViewById (R.id.button); textView=findViewById (R.id.text_view); button.setOnClickListener (this);} @ Override public void onClick (View view) {new Thread (new Runnable () {@ Override public void run () {/ / assuming a time-consuming operation is performed here, resulting in the resulting string data data= "Nice to meet you" Message message=new Message (); message.what=UPDATE_TEXT; handler.sendMessage (message);}}. Start ();}}

First of all, if you write this way, there must be no mistake! The program can also run normally. But IDE gave a warning: "This Handler class should be static or leaks might occur".

This warning means that when we use the Handler class, we should declare it static, otherwise it will cause a memory leak.

So, why is there a memory leak? The reason is:

First: when we send a Message object through the sendMessage () method of the Handler object, the Message object holds a reference to the Handler object (depending on this reference, after Looper fetches the Message object from the message queue, the Message object can be accurately dispatched back to the Handler object! ).

Second, when we create a Handler object in the main thread, to override its handleMessage () method, we use an anonymous inner class to create the Handler object. Both anonymous inner classes and non-static inner classes implicitly hold a reference to an external class! Therefore, the Handler object holds a reference to the external class MainActivity.

When the above two are combined, the problem arises: the Message object holds a reference to the Handler object, and the Handler object holds a reference to the MainActivity. So, MainActivity this activity can never be reclaimed by memory until Message is recycled! If the Message object is sent to the message queue in a child thread and has not been processed, the main thread in which the activity is located will also hang all the time and will not be reclaimed by memory. As a result, it can cause a memory leak.

I know why, so what's the solution? In fact, the previous warning has already given a solution. That is to create a Handler object through a static inner class, because the static inner class does not hold a reference to the external class object.

At this point, I naturally create a static inner class that inherits from the Handler class, and then rewrites its handleMessage method.

Private static class MyHandler extends Handler {@ Override public void handleMessage (Message msg) {}}

However, here is another problem! If I no longer hold references to the external class, how can I use the methods and objects of the external class? After all, I'm going to UI in the handleMessage () method.

For cases where static inner classes are used to avoid memory leaks while calling methods of external classes: weak references can be used! That is, we declare a weak reference to an external class object in the inner class. This allows you to call the methods of an external class without causing a memory leak.

The modified code is as follows:

Package com.shaking.androidthreadtest;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import java.lang.ref.WeakReference;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private static final int UPDATE_TEXT=1; private String data; private TextView textView; private static class MyHandler extends Handler {/ / causes the inner class to hold a weak reference to the external class private WeakReference weakReference / / complete weak reference initialization in the constructor MyHandler (MainActivity activity) {weakReference=new WeakReference (activity);} @ Override public void handleMessage (Message msg) {/ / obtain the reference to the external class object through the weak reference get () method MainActivity activity=weakReference.get (); activity.textView.setText (activity.data);}} / / create the Handler object private MyHandler handler=new MyHandler (this); @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState) SetContentView (R.layout.main_layout); Button button=findViewById (R.id.button); textView=findViewById (R.id.text_view); button.setOnClickListener (this);} @ Override public void onClick (View view) {new Thread (new Runnable () {@ Override public void run () {/ / assuming a time-consuming operation is performed here, resulting in the resulting string data data= "Nice to meet you"; Message message=new Message (); message.what=UPDATE_TEXT; handler.sendMessage (message)) }}). Start ();}} above is the content of this article on "how to implement asynchronous messaging mechanism in Android". I believe everyone has a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report