Asynctask of Android Threading operations

Source: Internet
Author: User


Comparison of Asynctask and handler

1) Asynctask implementation of the principle, and the advantages and disadvantages of the application

Asynctask, a lightweight asynchronous class provided by Android, can directly inherit Asynctask, implement asynchronous operations in a class, and provide interface feedback about the current level of asynchronous execution (UI progress updates can be implemented through an interface), and finally feedback the results of the execution to the UI main thread.

Advantages of Use:

L Simple, fast

L Process controllable


Disadvantages of using:

L becomes complex when multiple asynchronous operations are used and UI changes are required.

2) The principle of handler asynchronous implementation and the advantages and disadvantages of its application

When Handler is implemented asynchronously, it involves Handler, Looper, Message,thread four objects, the process of implementing asynchronous is the main thread starting thread (child thread) àthread (child thread) Run and generate Message-àlooper get a message and pass it to handleràhandler one by one to get the message in Looper and make UI changes.

Advantages of Use:

L Clear structure, clear function definition

L Simple and clear for multiple background tasks


Disadvantages of using:

L in a single background asynchronous processing, appear too much code, the structure is too complex (relativity)

Asynctask Introduction
Android's Asynctask is more lightweight than handler and is suitable for simple asynchronous processing.
The first thing to make clear is that Android has handler and Asynctask, both to not block the main thread (the UI thread), and that the UI update can only be done in the main thread, so asynchronous processing is unavoidable.


Android to reduce this development difficulty, provides the asynctask. Asynctask is a packaged background task class, as its name implies, an asynchronous task. Asynctask is a good package for the Thread+handler.

Asynctask directly inherits from the object class, where the position is android.os.AsyncTask. To work with Asynctask we are going to provide three generic parameters and overload several methods (at least one for overloading).



Asynctask defines three types of generic type params,progress and result.

The Params is the input parameter that initiates the task execution, such as the URL of the HTTP request.
Progress the percentage of background task execution.
Result background performs the final return of the task, such as String.

Students who have used Asynctask know that an asynchronous load of data must be overridden by the following two methods:

Doinbackground (Params ...) is performed in the background, and more time-consuming operations can be placed here. Note that it is not possible to manipulate the UI directly. This method is performed on a background thread, and it usually takes a long time to complete the task's main work. You can call Publicprogress (Progress ...) during execution. To update the progress of the task.
OnPostExecute (Result) is equivalent to the way handler handles the UI, where it is possible to use the resulting processing action UI in Doinbackground. This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method

You also have to rewrite these three methods, if necessary, but not necessarily:

Onprogressupdate (Progress ...) You can use the progress bar to increase user experience. This method executes on the main thread and is used to show the progress of the task execution.
OnPreExecute () Here is the interface when the end user calls Excute, and the progress dialog can be displayed here before the task executes before calling this method.
Oncancelled () The action to be made when the user calls Cancel

The Asynctask.cancle (True) method can be called when a thread is disconnected, and then the Oncancelled () method is called

Using the Asynctask class, here are a few guidelines to follow:

The instance of the task must be created in the UI thread;
The Execute method must be called in the UI thread;
Do not manually call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods;
The task can only be executed once, otherwise the exception will occur when multiple calls are made;

/** *layout XML **/<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent">    <ButtonAndroid:id= "@+id/execute"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Execute"/>    <ButtonAndroid:id= "@+id/cancel"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"android:enabled= "false"Android:text= "Cancel"/>    <ProgressBarAndroid:id= "@+id/progress_bar"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"android:progress= "0"Android:max= "+"style= "? Android:attr/progressbarstylehorizontal"/>    <ScrollViewAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content">        <TextViewAndroid:id= "@+id/text_view"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"/>    </ScrollView></LinearLayout>

/** *androidmanifest.xml **/ <  android:name= "Android.permission.INTERNET"/>

/***activity Code **/ PackageCom.scott.async;ImportJava.io.ByteArrayOutputStream;ImportJava.io.InputStream;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.HttpStatus;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpGet;Importorg.apache.http.impl.client.DefaultHttpClient;Importandroid.app.Activity;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {Private Static FinalString TAG = "Async_task"; PrivateButton Execute; PrivateButton Cancel; PrivateProgressBar ProgressBar; PrivateTextView TextView; PrivateMyTask Mtask; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.main); Execute=(Button) Findviewbyid (R.id.execute); Execute.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//Note the new task can only be executed once for each instance, or an exception will occurMtask =NewMyTask (); Mtask.execute ("Http://www.baidu.com"); Execute.setenabled (false); Cancel.setenabled (true);        }        }); Cancel=(Button) Findviewbyid (r.id.cancel); Cancel.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//cancels an executing task, the Oncancelled method will be calledMtask.cancel (true);        }        }); ProgressBar=(ProgressBar) Findviewbyid (R.id.progress_bar); TextView=(TextView) Findviewbyid (R.id.text_view); }        Private classMyTaskextendsAsynctask<string, Integer, string> {        //The OnPreExecute method is used to do some UI action before performing a background task@Overrideprotected voidOnPreExecute () {log.i (TAG,"OnPreExecute () called"); Textview.settext ("Loading ..."); }                //the Doinbackground method performs background tasks internally and cannot modify the UI within this method@Overrideprotectedstring Doinbackground (String ... params) {log.i (TAG,"Doinbackground (params ... params) called"); Try{HttpClient Client=Newdefaulthttpclient (); HttpGet Get=NewHttpGet (params[0]); HttpResponse Response=Client.execute (GET); if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {httpentity entity=response.getentity (); InputStream is=entity.getcontent (); LongTotal =entity.getcontentlength (); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); byte[] buf =New byte[1024]; intCount = 0; intLength =-1;  while(length = Is.read (BUF))! =-1) {baos.write (buf,0, length); Count+=length; //call Publishprogress to announce the progress, and finally the Onprogressupdate method will be executedPublishprogress ((int) ((Count/(float) total) * 100)); //to demonstrate progress, hibernate 500 millisecondsThread.Sleep (500); }                    return NewString (Baos.tobytearray (), "gb2312"); }            } Catch(Exception e) {log.e (TAG, E.getmessage ()); }            return NULL; }                //Onprogressupdate method for updating progress information@Overrideprotected voidonprogressupdate (Integer ... progresses) {log.i (TAG,"Onprogressupdate (Progress ... progresses) called"); Progressbar.setprogress (progresses[0]); Textview.settext ("Loading ..." + progresses[0] + "%"); }                //The OnPostExecute method is used to update the UI after performing a background task, displaying the results@Overrideprotected voidOnPostExecute (String result) {log.i (TAG,"OnPostExecute (result result) called");                        Textview.settext (result); Execute.setenabled (true); Cancel.setenabled (false); }                //The Oncancelled method is used to change the UI when canceling a task in execution@Overrideprotected voidoncancelled () {log.i (TAG,"Oncancelled () called"); Textview.settext ("Cancelled"); Progressbar.setprogress (0); Execute.setenabled (true); Cancel.setenabled (false); }    }}

Asynctask of Android Threading operations

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.