- Asynchronous Android Programming(Second Edition)
- Helder Vasconcelos
- 756字
- 2021-07-14 10:43:14
Introducing AsyncTask
AsyncTask
was introduced on the Android platform with Android Cupcake (API Level 3), with the express purpose of helping developers to avoid blocking the main thread. The Async part of the name of this class comes from the word asynchronous, which literally means that the blocking task is not occurring at the same time we call it.
The AsyncTask
encloses the creation of the background thread, the synchronization with the main thread, and the publishing of the progress of the execution in a single construct.
In contrast to the Handler
and Looper
constructs, the AsyncTask
exempts the developer from the management of low level components, thread creation, and synchronization.
AsyncTask
is an abstract class, and as such, must be subclassed for use. At the minimum, our subclass must provide an implementation for the abstract doInBackground
method, which defines the work that we want to get done off the main thread.
protected Result doInBackground(Params... params)
The doInBackground
is going to be executed in the current process in a parallel thread with the priority THREAD_PRIORITY_BACKGROUND
(Nice level 10) and with the name following the next form AsyncTask #<N>
.
Apart from the method doInBackground
the construct offers distinct methods which the developer might implement in the subclass to set up the task, publish progress, and post the final result into the main thread.
There are five other methods of AsyncTask
which we may choose to override:
protected void onPreExecute() protected void onProgressUpdate(Progress... values) protected void onPostExecute(Result result) protected void onCancelled(Result result) protected void onCancelled()
Although we could override one or more of these five methods, we will not invoke them directly from our own code. These are callback methods, meaning that they will be invoked for us (called back) at the appropriate time throughout the AsyncTask
lifecycle.
The key difference between doInBackground()
and the other four methods is the thread on which they execute.
Before any background work begins, onPreExecute()
will be invoked and will run synchronously to completion on the main thread when we call the execute (Params…) method.
In the onPreExecute
() method, we could set up the task or any progress dialog on the UI to indicate to the user that your task has just begun.
Once onPreExecute()
completes, doInBackground()
will be scheduled and will start work on a background thread.
During the background work, the developer can publish progress updates from doInBackground()
, which trigger the main thread to execute onProgressUpdate
with the progress values we provide. Internally, the AsyncTask
makes use of a Handler
bound to the main Thread Looper
to publish results on the main Thread as explained in Chapter 2, Performing Work with Looper, Handler and HandlerThread.
By invoking this on the main thread, AsyncTask
makes it easy for us to update the user interface to show progress (remember that we can only update the user interface from the main thread).
When the background work completes successfully, doInBackground()
may return a result. This result is passed to onPostExecute(),
which is invoked for us on the main thread. With the result received on the onPostExecute()
, we can update the user interface with the results of our background processing:
Note
This pattern of passing data from one thread to another is very important, because it allows us to run intensive and long tasks away from the crucial main thread. This construct simplifies the communication in the main thread and provides a high level API for executing asynchronous work on background threads.
Our AsyncTask
could manipulate fields of the enclosing Activity class, but then we would have to take extra precautions, such as adding synchronization to prevent race conditions and ensure visibility of updates.

Figure 3.1: AsyncTask callback execution function
The preceding figure displays a sequence of method calls executed by AsyncTask
, illustrating which methods run on the main thread versus the AsyncTask
background thread.
Note
Since onPreExecute()
, onProgressUpdate()
, onPostExecute()
, and onCancelled()
methods are invoked on the main thread, we must not perform long-running/blocking operations in these methods.
With the AsyncTask
reference invoking the cancel
method before doInBackground()
completes, onPostExecute()
will not be called. Instead, the alternative onCancelled()
callback method is invoked on the UI thread so that we can implement different behavior for a successful versus cancelled completion:

Figure 3.2: AsyncTask cancelled task execution sequence
The preceding figure displays the sequence of method calls when a task is cancelled before the doInBackground()
finishes. Like we have shown in the previous figure, the cancel()
might be called by the main thread or from any other thread with access to the AsyncTask
object reference.
- Mastering Entity Framework Core 2.0
- 兩周自制腳本語言
- Java Web基礎與實例教程(第2版·微課版)
- 體驗設計原理:行為、情感和細節
- 程序員考試案例梳理、真題透解與強化訓練
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- Apache Mesos Essentials
- 基于Swift語言的iOS App 商業實戰教程
- Apache Mahout Clustering Designs
- Go并發編程實戰
- SQL Server 2016數據庫應用與開發
- 青少年信息學競賽
- C語言程序設計
- 邊玩邊學Scratch3.0少兒趣味編程
- Distributed Computing with Python