Android Learning: Multithreading and asynchronous message processing mechanisms

Source: Internet
Author: User

  

In the recent process of learning the source code of Android project, encountered a lot of multithreading and asynchronous message processing mechanism. As a result of the knowledge of this piece is only a scratch, and there is no systematic understanding. But the repetition of the project made me realize the importance of this knowledge. So I sort out this blog, mainly on the meaning and usage of threading and asynchronous processing mechanisms, in order to help beginners to deepen their understanding of the asynchronous message processing mechanism, and to use the Asynctask tool class in the actual Android project to make UI updates in the child threads.

first, multi-threaded Android [1]

In Android, when a component of an application is started, and no other application components are running, the Android system opens a new thread for that application component to execute. By default, within the same Android application, the components inside are running in the same thread, which we call the main thread. When we start another component through a component, this is done by default in the same thread. Of course, we can manage the threads of our Android app on our own, and we can create additional threads for the application according to our own needs.

two, Main thread and Worker thread

In Android, threads are usually divided into two types, a thread called main thread, which can be referred to as worker thread except for the main thread. When an application is running, the Android operating system will start a thread for the application, which is our main thread, which is very important, it is mainly used to load our UI interface, to complete the interaction between the system and our users, And show the results of the interaction to our users, so the main thread is also called the UI thread.

The Android system does not create an additional thread for our application components by default, and all of these components run by default on the same thread. However, sometimes our UI thread is blocked when our application needs to complete a time-consuming operation, such as accessing the network or querying the database. For example, when we click on a button and want it to fetch some data from the network, if this is done in the UI thread, when we click on the button, the UI thread will be in a blocking state, and our system will not dispatch any other events, or worse, When our entire site is blocked for more than 5 seconds (as the authorities say), this is when the ANR (application not responding) phenomenon occurs, and the application pops up a box that lets the user choose whether to exit the program. For Android development, the phenomenon of ANR is absolutely not allowed.

Also, because our Android UI controls are thread insecure, we cannot manipulate our UI controls in threads other than UI thread. So in the multi-threaded programming of Android, we have two very important principles that must be adhered to:

    • Never take a time-consuming action in the UI thread, not blocking our UI thread
    • Cannot manipulate our UI elements in threads other than UI thread

three, multi-threaded common operation [2]

  1. Creating Threads

In Android, there are two methods for creating threads. (One is to create a thread object through the thread class's construction method, overriding the run () method implementation, and the other by implementing the Runnable interface.) )

/* First Method: */Thread Thread=new thread (new Runnable () {@Override public void run () {//action to be performed}});  Thread.Start (); /* The second method: */public class Mainactivity extends Activity implement runnable{@Override public    void Run () {    //To Action performed    }}

  2. Open Thread

  3. Thread hibernation

4, in the disconnection process  

  

Iv. How to handle communication between UI thread and Worker thread

Since there are two important principles to follow in Android, we may have questions? We can't handle time-consuming operations in the main thread, and we can't access our UI controls in a worker thread, so how can we update them to a UI control, like downloading a picture from the Web? This is related to the communication problem between our main thread and the worker thread. In Android, there are two ways to solve thread-direct communication problems, one is through the handler mechanism, and the other is the asynctask mechanism.

(i), handler mechanism

In the case of applications, Java applications on Android are the same on other systems, and they work by message-driven, and they generally work as follows:

(1), there is a message queue, you can post messages to this message queue.

(2), there is a message loop, the message is continuously removed from the message queue, and then processed.

In Android, a thread corresponds to a Looper object, and a Looper object corresponds to a MessageQueue (for storing a message). Next, let's look at several classes: The Looper class, the Message processing class handler, the message class.

 1. Message

A message is an inter-thread pass that can carry a small amount of information inside to exchange data between different threads, such as what field of message, and ARG1,ARG2 to carry some integer data, using the Obj field to carry an object. Message classes (messages) are stored in MessageQueue, and a MessageQueue can contain multiple message objects. Each message object can be obtained through the Message.obtain () method or the Handler.obtainmessage () method.

 2. Handler

Handler is the processor's intention, and is primarily used to send and process messages. Sending information is typically used by the handler SendMessage() method, and the messages sent are passed through a series of passes and are eventually delivered to the handler Handlemessage() method. The Message processing Class (Handler) allows you to send and process message and runnable objects into the MessageQueue of the thread in which they reside. It has two main functions:

(1), send the message or runnable application post () method or the SendMessage () method to MessageQueue, when sent, you can specify the delay time, send time or the bundle data to carry . When MessageQueue loops to the message, it is called by the corresponding handler object's Handlermessage () method to process it.

(2), communicating with the main thread in a child thread, that is, communicating with the UI thread in a worker thread. In addition, there can be only one looper and MessageQueue in a thread, but there may be multiple handler, and these handler can share a looper and MessageQueue.

3. MessageQueue

MessageQueue is the meaning of Message Queuing, which is primarily used to store all messages sent through handler. This part of the message will remain in the message queue and wait for it to be processed. There will only be one MessageQueue object in each thread.

4. Looper

Looper is the steward of MessageQueue in each thread, and after calling the Looper loop () method, it goes into an infinite loop, and whenever a message is found in MessageQueue, it is taken out. And passed to Handler's Handlemessage () method. The Looper object is used to open a message loop for a thread to manipulate the messgequeue. By default, the newly created thread in Android does not have a message loop turned on (except the main thread).

Asynchronous message processing mechanism flowchart [3]

Summarize the process as follows: First create a Handler object in the main thread and override the Handlemessage () method. Then, when a UI action is required in a child thread, a message object is created and sent through handler. The message is then added to the MessageQueue queue waiting to be processed, while Looper tries to remove the pending information from MessageQueue and finally sends it back to the Handlemessage () method of handler.

Because handler is created in the main thread, the Handlemessage () method also runs in the main thread, so you can rest assured that the UI is working.

public class Mainactivity extends Activity {private TextView TV;            Private Handler handler=new Handler () {public void Handlemessage (Message msg) {switch (msg.what) { Case 1://Gets the message Tv.settext (String) Msg.obj of the What property is 1;//fills the contents of the message into TextView BR            Eak            Default:break;    }        };          };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Button btn= (button) Findviewbyid (R.ID.BTN);        TV = (TextView) Findviewbyid (r.id.tv);                Btn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) { New Thread (New Runnable () {@Override public void                        Run () {message msg=new message (); Msg.obj= "You have clicked on the//message content msg.what=1;//Specify message handler.sendmessage (msg);//han                            dler send Message}}). Start ();    }        }); }}

(ii), Asynctask

Asynctask: The asynchronous task, literally, is to do something asynchronously when the main thread of our UI is running. Asynctask allows us to perform an asynchronous task in the background. We can place time-consuming operations in asynchronous tasks and update our UI controls at any time by returning the results of the task execution to our UI thread. By Asynctask we can easily solve the problem of communication between multiple threads, the advent of Asynctask tool class has greatly facilitated the UI operation in the sub-thread, but its nature is still the asynchronous message processing mechanism, but it is a good package for us to do Android [4].

How to understand Asynctask? In layman's terms, Asynctask is the equivalent of Android to provide us with a framework for multithreaded programming, between thread and handler, if we want to define a asynctask, we need to define a class to inherit Asynctask abstract class. , and implement its only one Doinbackgroud abstract method. To master Asynctask, we must have a concept, summed up is: 3 generics, 4 steps.

What are the 3 generic types referring to? Let's take a look at Asynctask's definition of this abstract class, and when we define a class to inherit asynctask, we need to specify 3 generic parameters for it:

Asynctask <params, Progress, result>

Params: This generic specifies the type of arguments we pass to the asynchronous task when it executes

Progress: This generic specifies the type of parameters that our asynchronous task will execute when it executes the progress returned to the UI thread

Result: The type of results returned to the UI thread after this generic specified asynchronous task finishes executing

When we define a class that inherits the Asynctask class, we must specify the three generic types, and if none are specified, write them void, for example:

Asynctask <void, Void, void>

4 steps: When we execute an asynchronous task, it needs to follow the following 4 steps to perform the respective

OnPreExecute (): This method is executed before the asynchronous task executes, and is executed in the UI thread, usually in this method we do some initialization of the UI controls, such as popup to give ProgressDialog

Doinbackground (params ... params): This method is executed immediately after the OnPreExecute () method is executed, which is the method to handle the asynchronous task. The Android operating system will open a worker thread in the thread pool in the background to execute our method, so this method is executed in the worker thread, and after this method executes, we can send our execution results to our last OnPostExecute method, in this method, we can get data from the network and some time-consuming operation

onprogressupdate (Progess ... values): This method is also executed in the UI thread, and we sometimes need to return the progress of execution to our UI interface when the asynchronous task executes, such as downloading a picture of the web , we need to show the progress of their downloads at all times, and we can use this method to update our progress. Before this method is called, we need to invoke a publishprogress (Progress) method in the Doinbackground method to pass our progress to the Onprogressupdate method all the way to update

OnPostExecute ( result ... result): When our asynchronous task executes, the result is returned to the method, which is also called in the UI thread. We can display the returned results on a UI control

Why is it that our Asynctask abstract class has only one Doinbackground abstract method?? The reason is that if we're going to do an asynchronous task, we have to open up a new thread for it to do something, and when this asynchronous task is done, I probably don't need to pop it to ProgressDialog, I do not need to update my ProgressDialog progress bar at any time, and I do not need to update the results to our UI interface, so there is no need for three methods other than the Doinbackground method, so the method we have to implement is Doinbackground method .

If you want to start this task, you need to execute the code for the structure such as method (). Execute (params):

    private void Task () {        new asynctask<string, Void, boolean> () {            @Override            protected Boolean Doinbackground (String ... params) {  /* pass multiple String arguments */                try {                    //execute time-consuming operation                } catch (Exception e) {                    //Print exception                }            }            @Override            protected void OnPostExecute (Boolean issuccess) {                if (issuccess) {                    //operation after successful operation                } else {                    //Print error                }            }        . Execute (params); /* Pass Parameters */

 

[1] xiaoluo501395377. Android Multi-threaded-----asynctask detailed. http://www.cnblogs.com/xiaoluo501395377/p/3430542.html.

[2] a silver meteor. Android threading and asynchronous message processing mechanism. http://www.cnblogs.com/scetopcsa/p/3661963.html.

[3] u012339794. Android asynchronous message processing mechanism. http://www.lai18.com/content/1849027.html.

[4] Guo Lin. First line of code ANDROID[J]. 2014.

Android Learning: Multithreading and asynchronous message processing mechanisms

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.