How to use and understand Asynctask

Source: Internet
Author: User

, for time-consuming operations, our general approach is to turn on "child threads." If you need to update the UI, you need to use handler

2, if the time-consuming operation too much, then we need to open too many sub-threads, which will bring a huge burden on the system, which will also lead to performance problems. In this case, we can consider using class Asynctask to perform tasks asynchronously, without the need for child threads and handler, to complete the asynchronous operation and refresh the UI.

3, Asynctask: The communication between the threads is packaged, is the background thread and the UI thread can easily communicate: the background thread executes an asynchronous task, and the result is communicated to the UI thread.

4. How to use: It is divided into two steps, custom asynctask, call the custom Asynctask in time-consuming place. You can refer to the following code example.

Step1: Inherit asynctask<Params,Progress,Result>

Params: input parameter. The corresponding parameter that is passed in the Excute () method is called in the class that calls the custom Asynctask. If you do not need to pass parameters, set it directly to void.

Progress: Percentage of child threads executing

Result: Returns the value type. The return value type of the Doinbackground () method remains the same.

Step2: Implement the following methods: Execution timing and function look at the sample code, the following description of the return value type and parameters

OnPreExecute (): no return value type. Do not pass parameters

Doinbackground (params ... params): The return value type and Result are consistent. Parameter: Pass void if none is available;

Publishprogress (params ... params): onprogressupdate (params ... values) is called directly upon execution of this method

Onprogressupdate (Params ... values): no return value type. Parameter: transfer void if none is available Progress

OnPostExecute (Result result): no return value type. Parameters: Consistent with Result .

Step3: Generates an object in the invocation of a custom asynctask class;

Execute: Object. Excute (params... params);

Small bet

1) The instance of the task must be created in the UI thread

2) The Execute method must be called in the UI thread

3) do not manually call OnPreExecute (), OnPostExecute (Result), doinbackground=\ ' #\ ' "onprogressupdate (Progress ...) These several methods

4) The task can only be executed once, otherwise an exception will occur when multiple calls are made

Example code:

 <?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" fill_parent          "><textview android:layout_width=" fill_parent "android:layout_height=" Wrap_content " Android:text= "Hello, Welcome to Andy ' s blog!" /> <button android:id= "@+id/download" android:layout_width= "Fill_parent" android:layout _height= "Wrap_content" android:text= "Download"/> <textview android:id= "@+id/tv" Andro Id:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "Current progress display"/> <P Rogressbar android:id= "@+id/pb" android:layout_width= "fill_parent" android:layout_height= "Wrap_con Tent "style="? Android:attr/progressbarstylehorizontal "/> </linearlayout> 

Package Sn.demo;import Android.content.context;import Android.os.asynctask;import android.util.log;import Android.widget.progressbar;import Android.widget.textview;public class Downloadtask extends AsyncTask<Integer,    Integer, string> {///behind angle brackets are parameters (thread break Time), progress (publishprogress used), return value type private Context mcontext=null;    Private ProgressBar Mprogressbar=null;    Private TextView Mtextview=null;        Public Downloadtask (Context context,progressbar pb,textview TV) {This.mcontext=context;        THIS.MPROGRESSBAR=PB;    THIS.MTEXTVIEW=TV;     }/* * First Execution method * Execution time: Called by the UI thread before performing the actual background operation: You can do some preparatory work in the method, such as displaying a progress bar on the interface, or instantiating some controls, this method can not be implemented. * @see Android.os.asynctask#onpreexecute () */@Override protected void OnPreExecute () {//TODO Auto-gene        Rated method Stub log.d ("Sn", "00000");    Super.onpreexecute (); }/* Execution time: Executes immediately after the OnPreExecute method executes, which runs in the background thread * role: mainly responsible for performing those very time-consuming background processing work. You can call the Publishprogress method toUpdates the real-time task progress.     The method is an abstract method that the subclass must implement. * @see Android.os.asynctask#doinbackground (params[]) */@Override protected String doinbackground (Integer ... par        AMS) {//TODO auto-generated Method Stub log.d ("Sn", "1111111");            for (int i=0;i<=100;i++) {mprogressbar.setprogress (i);            Publishprogress (i);            try {thread.sleep (params[0]);            } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();    }} return "execution complete"; }/* Execution time: This function is called when Doinbackground calls Publishprogress, and the UI thread calls this method. Although this method has only one parameter, this parameter is an array that can be invoked with Values[i] to invoke the function: The interface shows the progress of the task, for example, by displaying it through a progress bar. In this instance, the method is executed 100 times * @see android.os.asynctask#onprogressupdate (progress[]) */@Override protected void Onprog        Ressupdate (Integer ... values) {//TODO auto-generated Method Stub log.d ("Sn", "2222222222");      Mtextview.settext (values[0]+ "%");  Super.onprogressupdate (values); }/* Execution time: After Doinbackground execution completes, will be called by the UI thread * function: The results of the background will be passed through the method to the UI thread, and displayed to the user on the interface * Result: Above doinbackg Round the return value after execution, so here is "execution complete" * @see android.os.asynctask#onpostexecute (java.lang.Object) */@Override PROTECTE                d void OnPostExecute (String result) {//TODO auto-generated Method Stub log.d ("Sn", "3333333333");    Super.onpostexecute (result); }}
Package Sn.demo;import Android.app.activity;import Android.os.bundle;import android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.progressbar;import Android.widget.textview;public class Asynctaskdemoactivity extends activity {/** Called when the activity is first CRE Ated.    */private Button download;    Private TextView TV;    Private ProgressBar PB;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.main);    Initview ();        } private void Initview () {//TODO auto-generated Method Stub tv= (TextView) Findviewbyid (r.id.tv);        pb= (ProgressBar) Findviewbyid (R.ID.PB);        Download= (Button) Findviewbyid (r.id.download); Download.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View V           ) {//TODO auto-generated method stub     Downloadtask dt=new Downloadtask (ASYNCTASKDEMOACTIVITY.THIS,PB,TV);            Dt.execute (100);    }        }); }}

Reference connection

http://blog.csdn.net/cjjky/article/details/6684959

http://blog.csdn.net/zhenyongyuan123/article/details/5850389

Http://www.eoeandroid.com/thread-102664-1-1.html

How to use and understand Asynctask

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.