Android Async Task Asyntask

Source: Internet
Author: User

Android provides a set of classes specifically for asynchronous processing. That is: the Aynstask class. This class can be used to create a new thread for the time-consuming program to process and return after processing.
In fact, the Asyntask class is an encapsulation of the thread class, and some new methods are added. When programming, both can achieve the same functionality. The asyntask and thread are compared later in this article.
1. Asyntask class Structure
Several of the internal callback functions used by the Asystask class are:
Doinbackground ()

OnPreExecute ()

OnPostExecute ()

Onprogressupdate ()
Copy Code
It is these callback functions that make up the use logical structure of the Asyntask class.
Note: Each asyntask subclass must replicate at least the Doinbackground () method.
2. Callback Logic Relationship
Call relationships such as:



After the 1> main thread calls the Execute () method of the Asyntask subclass instance, the OnPreExecute () method is called first. OnPreExecute () runs in the main thread and can be used to write some start prompt code.
2> starts a new thread and calls the Doinbackground () method to perform asynchronous data processing.
When the 3> finishes processing, the asynchronous thread ends and the OnPostExecute () method is called in the main thread. OnPostExecute () can perform some end-of-tip processing.
Supplemental: When the Doinbackground () method is processed asynchronously, if you want to notify the main thread of some data (e.g., processing progress). At this point, you can call the Publishprogress () method. At this point, the main thread calls the Onprogressupdate () method of the Asyntask subclass for processing.
3, the transfer of data between various functions
Through the above call relationship, we can probably see some data transfer relationship. As follows:
Execute () is passed to Doinbackground ().
The return value of Doinbackground () is passed to OnPostExecute ().
Publishprogress () is passed to Progressupdate ().

Important: In order to invoke a relationship that is explicit and secure, the Asyntask class passes 3 generics when inheriting. The first generic corresponds to the delivery type of execute () to Doinbackground (). The second generic corresponds to the return type of Doinbackground () and the type passed to OnPostExecute (). The third generic corresponds to the type that publishprogress () passes to Progressupdate ().
The data passed is an array of the corresponding type, and the arrays are variable-length oh. Can be used according to the specific circumstances.

4. Example:
Looking at the above, you should have an understanding of the use logic of the Asyntask class. Let's write a simple example below.
The example function is simple: There are 1 TextView and botton in the activity. When you click Botton, the value of TextView is changed asynchronously, and the value is output with System.out.println () when the corresponding callback function executes.
Layout:
<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
android:orientation= "Vertical" >

<textview
Android:id= "@+id/text"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "@string/hello"/>
<button
Android:id= "@+id/button"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "Change"
/>

</LinearLayout>


Java code:
Import android.app.Activity;
Import Android.os.AsyncTask;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.TextView;

public class Ansytestactivity extends Activity {
/** called when the activity is first created. */

TextView text =null;
Button Button=null;
String Str=null;
Ansytry Anys=null;
Double result=0;

@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
text= (TextView) Findviewbyid (R.id.text);
button= (Button) Findviewbyid (R.id.button);
Str= "Wei";
Button.setonclicklistener (New Onclicklistener () {

@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
Anys=new ansytry (text);
Anys.execute (str);

}
});
}


Class Ansytry extends Asynctask<string, TextView, double>{

TextView Te=null;

Public Ansytry (TextView te) {
Super ();
This.te = te;
}

@Override
Protected Double doinbackground (String ... params) {
TODO auto-generated Method Stub
Double dou=0;
if (Params[0].equals ("Wei")) {
System.out.println (Thread.CurrentThread (). GetName () + "Recive Wei");
dou=100;
}
Publishprogress (TE);
return dou;
}

@Override
protected void OnPostExecute (Double result) {
TODO auto-generated Method Stub
Super.onpostexecute (result);
System.out.println ("PostExecute---double---" +result);
}

        @Override
        protected void OnPreExecute () {
           //TODO auto-generated Method Stub\
            System.out.println (" Pretexecute------");
            Super.onpreexecute ();
       }

        @Override
        protected void Onprogressupdate (TextView ... values) {
            TODO auto-generated Method Stub
            values[0]. SetText (Values[0].gettext () + "1");
            super.onprogressupdate (values);
       }
       
   }
}


5. Summary
It may seem complicated to see this asynchronous call relationship for the first time, but when you're familiar with it, you'll find that this structure works well. This structure encapsulates all the thread traffic as callback functions, and the invocation logic is easy to write. In particular, after the end of asynchronous processing, there are callback functions for finishing. If you are using the thread's Run () method, the run () does not return a value after the end. So you have to set up a communication mechanism. However, in fact, the use of handler+thread mechanism can actually replace Asyntask's call mechanism. As long as the handler object is passed to thread, it can be easily processed asynchronously. And this MVC pattern structure is more obvious, convenient management. So I think, the use of asyntask or handler+thread structure, personal preferences bar. But one thing you can clearly feel is that handler+thread is suitable for large-frame asynchronous processing, while Asyntask is suitable for small, simple asynchronous processing. All of these are personal points of view + understanding. A new point of view please point out.

Android Async Task Asyntask

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.