官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 社旗县| 平湖市| 皮山县| 石台县| 栖霞市| 长沙市| 海口市| 阳山县| 湘潭市| 房山区| 娄烦县| 应用必备| 阿图什市| 灵川县| 当阳市| 原平市| 马关县| 嘉定区| 祁连县| 固始县| 涞水县| 五莲县| 武威市| 新余市| 昭觉县| 监利县| 公主岭市| 滁州市| 富宁县| 页游| 将乐县| 静安区| 宜兰县| 南充市| 开远市| 固镇县| 廉江市| 寿宁县| 鸡东县| 祁东县| 隆化县|