Android Getting Started (17) Android multithreading

Source: Internet
Author: User

Original link: http://www.orlion.ga/670/

First, update the UI in a child thread

The UI is not allowed to be updated in the child threads in Android, but it can only be updated in the main thread, but we sometimes have to perform some time-consuming tasks on the child threads and then update the UI based on the results of the run, which gives Android a set of asynchronous message processing mechanisms.

To create a project Androidthreaddemo, modify the Activity_main.xml:

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"      Android:layout_width= "Match_parent"     android:layout_height= "Match_parent" >         <Button          Android:id= "@+id/change_text"         android:layout_width= "Match_ Parent "        android:layout_height=" Wrap_content "         android:text= "Change text"  />    <textview         android:id= "@+id/text"          android:layout_width= "Wrap_content"         android:layout_ height= "Wrap_content"         android:layout_centerinparent= "true"         android:text= "@string/hello_world"          android: Textsize= "20SP"/></relativelayout>

    mainactivity.java:

Package ga.orlion.androidthreaddemo;import android.app.activity;import android.os.bundle;import  android.os.Handler;import android.os.Message;import android.view.View;import  Android.view.view.onclicklistener;import android.widget.button;import android.widget.textview;public  class MainActivity extends Activity implements OnClickListener{public  Static final int update_text = 1;private textview text;private button  changetext;private handler handler = new handler ()  {public void  Handlemessage (message msg)  {switch  (msg.what)  {case UPDATE_TEXT://  Here you can do UI operation Text.settext ("Nice to meet you"); break;default:break;}}; @Overrideprotected  void oncreate (bundle savedinstancestate)  {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main);text =  (textView)  findviewbyid (r.id.text);changetext =  (Button)  findviewbyid (R.id.change_text); Changetext.setonclicklistener (this);} @Overridepublic  void onclick (view v)  {switch  (V.getid ())  {case r.id.change_ Text:new thread (new runnable ()  {@Overridepublic  void run ()  {message message  = new message (); Message.what = update_text;handler.sendmessage (Message);  //   Send the Message object past}}). Start ();; Break;default:break;}}}

Here we first define an integer constant Update_text, which is used to represent the update TextView action. Then add a handler object and rewrite the parent class's Handlemessage method, where the specific message is processed. If the value of the What field of the message is found to be equal to Update_text, change the contents of the TextView display to meet.

Here's another look at the code in the Click event of the Change Text button. As you can see, this time we did not directly perform UI operations on the thread, but instead created a Message (Android.os.Message) object and specified the value of its what field as Update_text, and then called Handler's The SendMessage () method sends this message out. Soon, handler receives this message and processes it in the Handlemessage () method. Note that the code in the Handlemessage () method is now running in the main thread, so we can safely do the UI here. Next, the value of the What field to carry with the message is judged, and if it equals Update_text, the contents of the TextView display are changed to meet.

Second, parsing asynchronous processing mechanism

Asynchronous processing in Android consists primarily of four parts, Message, Handler, MessageQueue, and Looper

1.Message

The message is a messaging between threads that can carry a small amount of information inside to exchange data between different threading, in which we use the What field of the message, in addition to using the Arg1 and Arg2 fields to carry the integer data. Using the obj field to carry a single object

2.Handler

Handler, as the name implies, is the meaning of the processor, which is primarily used to send and process messages. Sending a message is typically using the handler SendMessage () method, and the emitted message is eventually passed to the handler Handlemessage () method after a series of tossing and processing.

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 enters into an infinite loop, and then whenever a message is found in MessageQueue, It is removed and passed to the handler Handlemessage () method. There will be only one Looper object in each thread.

The entire process of asynchronous message processing: You first need to create a handler object in the main thread, and override the Handlemessage () method, and then create a message object when a child thread needs to do a UI operation, and send the message through handler. The message is then added to the MessageQueue queue for processing, while Looper attempts to remove the pending message from MessageQueue and finally distribute the Handlemessage () method handler. Since handler is created in the main thread, the code in the Handlemessage () method is also executed in the main thread.

After a message has been called by such a process, it goes from the child thread to the main thread, never

The update UI becomes the UI that can be updated, and so is the core idea of the entire asynchronous message processing.

Third, the use of Asynctask

Asynctask is an abstract class that, when inherited, we can specify three generic parameters for the Asynctask class, and the purpose of these three parameters is as follows:

1.Params

Parameters that need to be passed in when executing asynctask can be used in a background task

2.Progress

When the background task executes, if you need to display the current progress on the interface, use the generic type specified here as the progress unit

3.Result

When the task finishes executing, if you need to return the result, use the generic type specified here as the return value type

Therefore, one of the simplest custom asynctask can be written as follows:

Class Downloadtask extends Asynctask<void, Integer, boolean>{}

Here we specify the first generic parameter of Asynctask as void, which means that there is no need to pass parameters to the background task when executing asynctask. The second release parameter, specified as Integer, indicates that the integer data is used as the progress display unit. The third generic parameter, specified as Boolean, indicates that the execution result is fed back using Boolean data.

Now that we have custom downloadtask or an empty task, and cannot do any actual work, we also need to take several methods in the rewrite Asynctask to complete the task customization. There are four ways to rewrite often:

1.onPreExecute ()

This method is called before the background task executes and is used for initialization on some interfaces, such as displaying a progress bar dialog box

2.doInBackground (Params ...)

All the code in this method will run in a sub-thread, and we should be here to handle all the time-consuming tasks. Once the task is completed, the result of the task execution can be returned by the return statement, and if Asynctask's third generic parameter specifies void, the task execution result is not returned. Note that the UI action is not allowed in this method, and if you need to update the UI elements, such as feedback on the progress of the current task, you can call Publishprogress (Progress ... ) method to complete the

3.onProgressUpdate (Progress ...)

When Publishprogress (Progress ...) is called in a background task Method, the method is called quickly, and the parameters that are carried in the method are passed in the background task. The UI can be manipulated in this method, and the interface elements can be updated accordingly using the values in the parameters.

4.onPostExecute (Result)

This method is called quickly when the background task is completed and returned through a return statement. The returned data is passed as a parameter to this method, and the returned data can be used to perform some UI actions, such as reminding the result of the task execution, and closing the Progress Bar dialog box.

Therefore, a complete custom asynctask can be written as follows:

class downloadtask extends asynctask<void, integer, boolean> {      @Override     protected void onpreexecute ()  {         progressdialog.show (); //  Show progress dialog box     }      @Override     protected boolean doinbackground (void... params)  {        try {             while  (True)  {                 int downloadpercent = dodownload (); //  This is a fictional approach                  Publishprogress (downloadpercent);                 if (downloadpercent >= 100)  {                     break;                 }             }        } catch  (exception e)  {             return false;         }        return true;     }     @Override     protected void onprogressupdate ( integer... values)  {        //  update download progress here          progressdialog.setmessage ("downloaded "  + values[0] +   "%");     }     @Override     protected void onpostexecute ( Boolean result)  {        progressdialog.dismiss ();  //   Close Progress dialog box         //  prompt for download results here          if  (Result)  {             toast.maketext (context,  "download succeeded",             toast.length_short). Show ();         } else  {            toast.maketext (context,  "  download failed ",             Toast.length_short). Show ();         }    }}

In this downloadtask, we perform specific download tasks in the Doinbackground () method. The code in this method runs in a sub-thread, so it does not affect the running of the main thread. Note that a dodownload () method is invented, which is used to calculate the current download progress and return, and we assume that this method already exists. After getting the current download progress, the following should consider how to display it to the interface, because the Doinbackground () method is running in a sub-thread, there is certainly no UI operation here, so we can call Publishprogress () Method and pass in the current download progress so that the Onprogressupdate () method will be called quickly and the UI can be manipulated here.

When the download is complete, the Doinbackground () method returns a Boolean variable so that the OnPostExecute () method is called quickly, and this method is also run in the main thread. Then we will pop up the corresponding toast prompt based on the results of the download, thus completing the entire Downloadtask task.

To put it simply, the trick to using Asynctask is to perform specific time-consuming tasks in the Doinbackground () method, UI operations in the Onprogressupdate () method, and in the OnPostExecute () method to perform some task finishing work.

If you want to start this task, just write the following code:

New Downloadtask (). Execute ();

Android Getting Started (17) Android multithreading

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.