The Asyctask of the Android asynchronous task mechanism

Source: Internet
Author: User

There are two ways to implement the asynchronous task mechanism in Android, Handler and Asynctask. This article is about the asynchronous implementation of Asynctask.

1. When to use Asnynctask

In the previous article has been said that the main thread is responsible for controlling the UI page display, update, interaction and so on. For a better user experience, the shorter the operational requirements in the UI thread, the better.

We put time-consuming operations (such as network requests, database operations, complex computations) into separate sub-threads to avoid blocking the main thread. However, you cannot update the UI interface in a child thread, and you need to use handler.

But if too much time consuming, then we need to open too many sub-threads, which will put 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.

Don't feel free to use asynctask unless you have to interact with the UI thread. By default, thread is used, so be aware that you need to lower the priority of the threads. Asynctask is suitable for short-time operations, long-term operations, such as downloading a large video, which requires you to use your own threads to download, whether it is a breakpoint download or other.

2, Asnynctask principle

Asynctask has two main parts: one is the interaction with the main thread, and the other is the management scheduling of threads. Although it is possible to have multiple instances of Asynctask subclasses, the internal handler and threadpoolexecutor of Asynctask are shared by the process, are static, or belong to the class, and the properties of the class are scoped to Classpath , because a process is a VM, it is asynctask that controls all instances of subclasses in the process scope.

Asynctask internally creates a process-scoped thread pool to manage the tasks to run, which means that when you call the Execute () method of Asynctask, Asynctask will give the task to the thread pool, The thread pool is managed to create the thread and run Therad.

3, Asynctask Introduction

Android's Asynctask is more lightweight than handler (just lighter on the code, and actually more resource-intensive than handler), for simple asynchronous processing.
  
Android has handler and Asynctask, all in order not to block the main thread (UI thread), because the UI update can only be done in the main thread, so asynchronous processing is unavoidable.

Asynctask: The communication between threads is wrapped, which is that the background thread and the UI thread can easily communicate: the background thread executes the asynchronous task, and the result is communicated to the UI thread.

The use of Asynctask is divided into two steps:

① inherits the Asynctask class to implement its own class

Public abstract class Asynctask<params, Progress, result> {
Params: input parameter corresponding to the parameter passed in the Excute () method. If you do not need to pass parameters, set it directly to void. Progress: Percentage of background task execution result: Returns a value type that is consistent with the return value type of the Doinbackground () method.

② Replication method

At a minimum, rewrite the following two methods:

      • Doinbackground (Params ...)

        You can call Publishprogress (Progress ...) in this method by performing a more time-consuming operation in a child thread (the other method is executing on the main thread), not updating the UI. To update the progress of the task. The progress method is asyctask in which a final method can only be called and cannot be overridden.

      • OnPostExecute (Result)

        Using the results obtained in doinbackground processing operation UI, the main thread executes, and the result of the task execution is returned as a parameter to this method.
          
        Sometimes the following three methods are implemented as required:

      • 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 you can display the progress dialog box here before the task executes before calling this method.

      • Oncancelled ()

        Action to be made when the user calls Cancel

4. Asynctask Example

Follow the steps above to define your own asynchronous class:

 Public classMyTaskextendsAsynctask<string, Integer, string> {      //The first method performed is used to do some UI action before performing a background task@Overrideprotected voidOnPreExecute () {}//second execution method, executed after OnPreExecute (), for background tasks, no UI modification within this method@Overrideprotectedstring Doinbackground (String ... params) {//processing time-consuming operations        return"Background Task execution Complete"; }     /*This function is triggered when Doinbackground calls publishprogress (int i), although there is only one argument to be called, but here is an array, so use progesss[0] to take the nth parameter for the value Progress[n ] to take the value*/@Overrideprotected voidonprogressupdate (Integer ... progresses) {//"Loading ..." + progresses[0] + "%"        Super. Onprogressupdate (progress); }      /*Doinbackground is triggered on return, in other words, the result of Doinbackground is triggered after execution is the return value of the above doinbackground execution, so this is "background task execution complete"*/@Overrideprotected voidOnPostExecute (String result) {}//The Oncancelled method is used to change the UI when canceling a task in execution@Overrideprotected voidoncancelled () {}}

When the main thread declares the object of the class, the Execute () function of the calling object begins execution.

New MyTask (); T.execute (); // There are no parameters here

5, the use of asynctask need to pay attention to the place

    • Asnyctask internal handler need to interact with the main thread, so the instance of Asynctask must be created in the UI thread

    • The Asynctaskresult Doinbackground (Mparams) method executes an asynchronous task that runs in a child thread, and other methods run in the main thread to manipulate the UI component.

    • A asynctask task can only be executed once.

    • The Asnyctask object's Cancel (Boolean) method can be called at any time in the run, and if successful, call IsCancelled () returns True and the OnPostExecute () method is not executed, but instead Oncancelled () method.

    • For asynchronous tasks that you want to start executing immediately, either use thread directly or create a separate thread pool for asynctask. The default asynctask does not necessarily perform your task immediately unless you provide him with a separate thread pool. If you do not interact with the main thread, create a thread directly.

The Asyctask of the Android asynchronous task mechanism

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.