Android Thread Management Asynctask asynchronous task (iv)

Source: Internet
Author: User

Objective:

The previous several articles mainly learned the thread as well as threads pool's creation and the use, today to learn the Asynctask asynchronous task, learns under Asynctask What solves the problem? But what is its disadvantage? What is the so-called enemy victorious!

Create a background:

We all know that the Android application is a single threaded model, in which the child threads cannot directly manipulate the UI main thread, must pass the handler mechanism, want to understand this knowledge can refer to this article: Android message Delivery handler message mechanism (a), So based on this consideration, we generally use Thread+handler to handle more time-consuming operations, but we all know that each time new thread () is expensive and lacks management, called a wild thread, and can be created indefinitely, competing with each other, Can lead to excessive use of system resources resulting in system paralysis, not conducive to expansion, such as timed execution, periodic execution, thread interruption, then we introduced the concept of thread pool, the whole problem-solving model becomes Runnable+executor+handler, In order to reduce the developer's development difficulty, Asynctask came into being, Asynctask is an encapsulation of the thread pool, using its custom Executor to schedule how threads are executed (concurrently or serially), and use Handler to complete the sharing of child threads and main thread data.

Asynctask Introduction

Asynctask is a lightweight asynchronous class provided by Android that can directly inherit Asynctask, implement asynchronous operations in a class, and provide interface feedback about the current level of asynchronous execution, and finally feedback the execution results to the UI main thread.

Asynctask main parameters, function parsing 1.) Asynctask is an abstract class. Asynctask defines three generic type params,progress and result
    • Params input parameters for initiating task execution, such as download URL
    • Progress Percentage of background task execution, such as download progress
    • Result background The results of the final return of the task, such as download results
2.) Inherited functions that can be implemented by Asynctask
    • OnPreExecute ()//This function is called running in the UI thread before the task is executed by the thread pool, such as now a wait for download progress progress, can not be implemented
    • Doinbackground (params ... params)//This function is called to run in a child thread when the task is executed by the thread pool, and in this case a more time-consuming operation such as performing a download, this function is an abstract function that must be implemented
    • Onprogressupdate (Progress ... values)//This function is a task in the thread pool execution is in running state, the progress of the callback to the UI main thread such as upload or download progress, also can not be implemented
    • OnPostExecute (Result result)//This function task thread pool execution end, callback to the UI main thread results such as download results, also can not be implemented
    • oncancelled (Result result)/oncancelled ()//This function indicates that the task is closed
3.) Asynctask main public functions
    • Cancel (Boolean mayinterruptifrunning)//attempts to cancel execution of this task, if the task has ended or has been canceled or cannot be canceled or for some other reason, it will cause this operation to fail, when this method is called, This method executes successfully and the task is not executed, and the task is no longer executed. If the task has already started, and the parameter passed in to this operation is mayinterruptifrunning true, the thread performing this task will attempt to break the task
    • Execute (params ... params)//Perform this task with the specified parameters, this method will return the task itself, so the caller can have a reference to this task. This method must be called in the UI thread
    • Executeonexecutor (Executor exec,params ... Params)//run in the specified thread pool with the specified parameters, this method will return the task itself, so the caller can have a reference to this task. This method must be called in the UI thread
    • Get ()//wait for the calculation to end and return the result
    • Get (long timeout, timeunit unit)//wait for the calculation to end and return the result, the maximum wait time is: timeout (Time Out)
    • GetStatus ()//Get the current state of the task PENDING (wait for execution), RUNNING (running), finished (run complete)
    • IsCancelled ()//Returns TRUE if the task succeeds before the task ends correctly, otherwise false
Asynctask Example: 1.) Simulate the need for a download file
String url = "Www.xxx.jpg"; Asynctask<string, Integer, string> asynctask =NewAsynctask<string, Integer, string>() {@Overrideprotected voidOnPreExecute () {//This function is called to run in the UI thread before the task is executed by the thread pool, such as now a wait for download progress Progress                Super. OnPreExecute (); LOG.E (TAG,"Asynctask OnPreExecute"); } @OverrideprotectedString Doinbackground (string[] params) {//This function is called when the task is executed by the thread pool and is run in a child thread, where it takes more time-consuming actions such as downloadingString URL = params[0]; LOG.E (TAG,"Asynctask doinbackground URL---->" +URL); //Simulation Download                inti = 0;  for(i = +; I <=; i + = 20) {                    Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } log.e (TAG,"Asynctask doinbackground result--progress-->" +i);                Publishprogress (i); The String result= "Download End"; returnresult; } @Overrideprotected voidOnprogressupdate (Integer ... values) {//This function is a task in the thread pool execution is in the running state, the progress of the callback to the UI main thread such as upload or download progress                Super. Onprogressupdate (values); intprogress = Values[0]; LOG.E (TAG,"Asynctask onprogressupdate Progress---->" +progress); } @Overrideprotected voidOnPostExecute (String s) {//This function is executed at the end of the thread pool, and the result of the callback to the UI main thread, such as download results                Super. OnPostExecute (s); LOG.E (TAG,"Asynctask onpostexecute result---->" +s); } @Overrideprotected voidOncancelled () {//This function indicates that the task is closed                Super. oncancelled (); LOG.E (TAG,"Asynctask oncancelled"); } @Overrideprotected voidOncancelled (String s) {//This function indicates that the task is closed and the execution result may be null                Super. oncancelled (s); LOG.E (TAG,"Asynctask oncancelled---->" +s);        }        }; Asynctask.execute (URL);

Run results

2.) How to close a Asynctask
Boolean mayinterruptifrunning True If the case is passed false
   if (! asynctask.iscancelled ()) {        boolean iscancel = Asynctask.cancel (true);        " Asynctask iscancel----> "+ iscancel);   }

Run Result: Test finds run as result

As you can see from the results above, the result is the same regardless of whether mayinterruptifrunning passed in true or false, that is, after we call the Cancel (Boolean mayinterruptifrunning) function, After Doinbackground () return, we will call oncancelled (object) not called OnPostExecute (object), but according to the results of the operation, we do not really terminate the child thread through this function to continue to run, Just by discarding the result of the run, Asynctask does not end a thread without considering the result. Calling Cancel () is actually setting a "canceled" state for Asynctask. It's up to you to check if Asynctask has been canceled, and then decide whether or not to terminate your operation. For mayinterruptifrunning--it does just make a interrupt () call to a running thread. In this case, your thread is non-interruptible and will not terminate the thread, we can periodically check the iscancelled () state in the Doinbackground (params. params), and terminate the time-consuming operation if the check is closed. For example, the above download can be changed to

@OverrideprotectedString Doinbackground (string[] params) {//This function is called when the task is executed by the thread pool and is run in a child thread, where it takes more time-consuming actions such as downloadingString URL = params[0]; LOG.E (TAG,"Asynctask doinbackground URL---->" +URL); //Simulation Download                inti = 0;  for(i = +; I <=; i + = 20) {                    if(iscancelled ()) { Break; }                    Try{Thread.CurrentThread (). Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } log.e (TAG,"Asynctask doinbackground result--progress-->" +i);                Publishprogress (i); }                if(iscancelled ()) {return"Download Cancel"; The String result= "Download End"; returnresult; }

Run results

Asynctask Places to note: 1.) Life cycle

Asynctask does not bind the life cycle with any component, so it is best to call Cancel (Boolean) in Activity/fragment () when creating execution asynctask in activity/or fragment;

2.) Memory leaks

If Asynctask is declared as a non-static inner class of activity, then Asynctask retains a reference to the activity that created the asynctask. If the activity has been destroyed, Asynctask's background thread is still executing, and it will continue to keep the reference in memory, causing the activity to not be recycled, causing a memory leak.

3.) Lost Results

Screen rotation or activity is killed in the background by the system, etc. will cause the activity to re-create, the previous run Asynctask will hold a previous activity reference, this reference is invalid, then call OnPostExecute () The update interface will no longer take effect.

4.) Parallel or serial

In versions prior to Android 1.6, Asynctask was serial, in the 1.6 to 2.3 version, and changed to parallel. The version after 2.3 has been modified to support both parallel and serial, execute the Execute () method directly when you want to execute it serially, and execute Executeonexecutor (Executor) If parallel execution is required

Android Thread Management Asynctask asynchronous task (iv)

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.