Reprint please specify the original address: http://www.cnblogs.com/ygj0930/p/7520700.html
One: Basic concepts
UI thread: When the Android program starts for the first time, Android launches a main thread, which is primarily responsible for handling UI-related events, such as user keystroke events, screen drawing events, and distributing related events to the corresponding component for processing. The main thread is often called the UI thread, and Android only allows the UI thread to modify the UI components in the activity.
Child thread: The thread created and started in the activity of the program is a child thread, and the UI component cannot be manipulated in a child thread.
Background tasks: Background tasks are typically done with child threads, and are often used to perform time-consuming tasks such as complex computations, downloading files, and so on. Because these operations work concurrently with the UI thread, they are also referred to as asynchronous operations.
Two: The asynchronous way--message passing mechanism
We know that only the UI thread can modify and manipulate the interface components, so how does the information in the other sub-threads be reflected in the UI? That requires the child thread to summarize the information into the UI thread, which is displayed on the component by the UI thread.
This process is the message passing mechanism.
1) message passing mechanism schematic diagram
2) message passing mechanism explanation
First, the UI thread maintains a Message Queuing MessageQueue, a circulator Looper, a processor handler: The message queue is responsible for accepting, storing the messages sent by other sub-lines Cheng, waiting for the UI thread to process, and the Circulator keeps polling the message queue, Extracts the first message of the team each time; The processor is responsible for processing the looper extracted messages and is responsible for rendering the results in the UI. WhereMessageQueue and Looper are automatically created and run as the UI thread starts, handler needs to be defined manually .
Second, a child thread is created and started in the UI thread, and a child thread is sent by the same handler (usually the handler is a global variable in the Acticity code, so the child thread is visible) to send the message. The message is then sent to the handler corresponding message queue of the current UI thread.
3) Implementation steps
Based on the principle of the messaging mechanism, we only need to implement the necessary things for each link.
First: Define, create handler, override the Handlermessage method, process the message
Private New Handler () { @Override publicvoid handlemessage (Message msg) { Switch (msg.what) { // According to the content of the message, for processing }}} ;
Then: Define the child thread in which to define the Send message statement
New Runnable () { @Override publicvoid run () { new Message (); = message label; Mhandler.sendmessage (message); // handler is a handler in the UI thread } };
Finally: Depending on the condition, create the child thread instance and start
New Thread (runnable); Mthread.start ();
4) Application Scenarios
The handler mechanism is suitable for the existence of multiple sub-threads, so that the information sent by multiple strand Cheng can be processed and rendered uniformly in the UI thread.
Attached: If you need to use handler and Looper in a child thread, you need to get to the handler, Looper object in the UI thread. Specific methods see: http://blog.csdn.net/logicteamleader/article/details/46591499 "
Three: Single asynchronous task--asynctask
The messaging mechanism looks more complex and involves the application of Message Queuing, which is almost a pattern that is used by the architectural dimension of a large Web application.
If it's just a single asynchronous task, it's a bit too cumbersome to use the messaging mechanism, so Android provides us with an auxiliary class--asynctask.
The Asynctask class, which can be understood as an asynchronous task performer , is designed to "perform a more time-consuming asynchronous task (up to a few seconds) and then update the interface".
1: Using Asynctask
1) Inherit Asynctask, define subclasses, and override several of these methods:
Asynctask needs to rewrite 5 methods, namely:
1. OnPreExecute method: Ready to run, the callback function is called by the UI thread immediately after the task is executed, and the progress bar can generally be displayed.
2. Doinbackground (Params ...) Method: Running in the background, usually here to perform time-consuming background calculations, the results are returned to the function, if Asynctask's third argument is void, you do not need to return, here can not update the UI, but it is possible to call Publishprogress (Progress ...) Method is complete.
3, Onprogressupdate (Progress ...) Method: Progress update, UI thread in Publishprogress (Progress ...) Called when the method call is complete, and a progress is generally displayed dynamically.
4, OnPostExecute (Result) method: Completes the background task, will return, here can carry on the UI operation, for example reminds the task to execute the result, as well as closes the progress Bar dialog box and so on.
5. Oncancelled method: Cancels the task, called when the Cancel () method of Asynctask is called.
classViewcontenttaskextendsAsynctask<void, Integer, boolean>{//three paradigms correspond to the parameter types of the following doinbackground, Onprogressupdate, OnPostExecute three methods, respectively @OverrideprotectedBoolean doinbackground (Void ... voids) {return NULL; } @Overrideprotected voidonprogressupdate (Integer ... values) {} @Overrideprotected voidOnPostExecute (Boolean b) {//Manipulate UI components} @Overrideprotected voidOnPreExecute () {} @Overrideprotected voidoncancelled () {}}
2) Create an asynchronous task instance to start an asynchronous task
Viewcontenttask New viewcontenttask (); Task.execute ();
2:asynctask Working principle
When an asynchronous task is executed, it goes through four steps:
OnPreExecute (), executed in the UI thread, is executed before the asynchronous task starts, and is typically used to set task parameters;
Doinbackground, the most important method to execute in a child thread (in fact, only it executes in a child thread, other methods are executed in the UI thread). When the OnPreExecute is finished, this method executes immediately, it is used for the background of the time-consuming calculation, the parameters of the asynchronous task will be passed to it, the execution of the results will be sent to the fourth step; on the way, it can also call the Publishprogress method to notify the UI thread of the current execution of the progress;
onprogressupdate, when Publishprogress is called, it executes in the UI thread, refreshes the task progress, and is generally used to refresh the UI widgets such as the progress bar;
OnPostExecute, when the asynchronous task in the background completes, it is called in the UI thread and gets the result of completion of the asynchronous task execution.
Android Learning Note 10: Asynchronous processing