Questions about the use and disadvantages of AsyncTask, questions about asynctask

Source: Internet
Author: User

Questions about the use and disadvantages of AsyncTask, questions about asynctask

(1) Introduction

1. AsyncTask is a lightweight asynchronous task class. It encapsulates Handler and Thread internally, so that the data of sub-threads can be easily transmitted to the UI Thread and updated. however, it is not suitable for time-consuming tasks. for time-consuming tasks, we recommend that you use a thread pool.

(1)Key APIs

1. Three parameters: Params, Progress, and Result. If AsyncTask does not need to pass specific parameters, the three generic parameters can be replaced by Void.

A, Params,Parameter type

B, ProgressIndicates the progress of background tasks.

C, ResultType of the result returned by the background task

2. Four parameters:

OnPreExcute (), DoInBackGround (), onProgressUpdate (), onPostExcute ();

A, onPreExcute (),It is executed in the main thread and called before the asynchronous task. It can be used for preparation before the task, such as the display of the Progress circle.

B, DoInBackGround (),Run in the thread pool to process time-consuming tasks. Publish the progress through publishProgress (). Then return the result through return.

C, onProgressUpdate (),Run the command in the main thread to obtain the latest progress of the task.

D, onPostExcute (),It is executed in the main thread to receive the result of an asynchronous task.

E, onCancelled (),It is also executed in the main thread. When the asynchronous task is canceled, onCancelled () will be called. At this time, onPostExecute () will not be called, but note that, the cancel () method in AsyncTask does not actually cancel the task, but sets this task to canceled. We need to judge the termination of the task in doInBackground. To terminate a thread, call the interrupt () method to mark the thread as interrupted. You need to mark the thread inside the thread and then interrupt the thread.


)

(3)Code usage:

@ Override
Protected voidOnCreate (@ Nullable Bundle savedInstanceState ){
Super. OnCreate (savedInstanceState );
SetContentView (R. layout.Activity_main);
MProgressDialog=NewProgressDialog (This);
NewDownloadtask(cmd.exe cute ();
}
ClassDownloadTaskExtendsAsyncTask {
@ Override
Protected voidOnPreExecute (){
MProgressDialog. Show ();
}
@ Override
ProtectedBoolean doInBackground (Void... params ){
Try{
While( True){
IntDownloadPercent = doDownload ();
PublishProgress (downloadPercent );
If(DownloadPercent >=100 ){
Break;
}
}
} Catch(Exception e ){
Return false;
}
Return true;
}
@ Override
Protected voidOnProgressUpdate (Integer... values ){
MProgressDialog. SetMessage ( "Current download progress :"+ Values [0] + "%");
}
@ Override
Protected voidOnPostExecute (Boolean result ){
MProgressDialog. Dismiss ();
If(Result ){
Toast. MakeText(ActivityA. This, "Download successful", Toast. LENGTH_SHORT). Show ();
} Else{
Toast. MakeText(ActivityA. This, "Download failed", Toast. LENGTH_SHORT). Show ();
}
}
}

(4)Note:

1. An AsyncTask object can only be created once. That is to say, the excute () method can only be called once. Otherwise, an exception will be reported during running.

2. AsyncTask must be created in the main thread and loaded in the main thread.

(5)Disadvantages:

1. Lifecycle

AsyncTask is not bound to any component, so it is best to call cancel (boolean) in onDestory () of Activity/Fragment when creating and executing AsyncTask in Activity/or Fragment );

2. Memory leakage

If AsyncTask is declared as a non-static internal class of the Activity, AsyncTask retains a reference to the Activity that created AsyncTask. If the Activity has been destroyed and the background thread of AsyncTask is still executing, it will keep this reference in the memory, so that the Activity cannot be recycled, causing memory leakage.

3. Lost results

If the screen rotation or Activity is killed by the system in the background, the Activity will be re-created. The previously running AsyncTask (non-static internal class) will hold a reference to the previous Activity, this reference is invalid. Calling onPostExecute () to update the interface will no longer take effect.

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.