Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android-AsyncTask的javadoc文檔

Android-AsyncTask的javadoc文檔

編輯:關於Android編程


android.os.AsyncTask
AsyncTask允許簡單適當的使用UI線程。這個類允許執行後台操作,然後把結果發布到UI線程,同時又免去了手動的操作線程或者是handler。

AsyncTask被設計成是線程和Handler的幫助類,並沒有構建一個通用的線程框架。
AsyncTask理想的使用場景是用於執行時間短的操作(最多幾秒)
如果你需要讓線程長時間執行,強烈推薦使用java.util.concurrent包下面提供的api,比如: Executor, ThreadPoolExecutor和FutureTask。

一個異步的任務指的是運行在後台線程上的操作,它的執行結果會發布到UI線程上。
一個異步任務是由3個泛型類型(Params, Progress和Result)和4個執行步驟來表示的(onPreExecute, doInBackground, onProgressUpdate和onPostExecute)。
 

使用
必須是AsyncTask的子類才可以使用,子類需要覆蓋至少一個方法(doInBackground),大多數都會覆蓋第二個(onPostExecute)方法。

這是一個例子:
private class DownloadFilesTask extends AsyncTask {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog(Downloaded + result + bytes);
}
}
一旦創建以後,就可以很簡單的執行任務:
new DownloadFilesTask().execute(url1, url2, url3);

AsyncTask的泛型參數
AsyncTask的三個泛型參數如下:
Params:傳遞給異步任務的參數
Progress:後台任務執行的進度
Result:後台任務執行的結果
並不是所有的異步任務都需要這三個參數,若果不需要,可以簡單地置為Void,如下:
private class MyTask extends AsyncTask { ... }

四個步驟
異步任務在執行的時候,會經歷4個步驟:
onPreExecute:在任務開始之前,被UI線程調用。這個一般是用來設置任務,比如在用戶界面顯示一個進度條。

doInBackground:在onPreExecute()執行完以後,立即被後台線程執行。這一步是用來執行後台計算,這可能會執行很長時間,異步任務的參數會傳遞進來。
這一步運行的結果必須要返回出去,然後傳遞給最後一步。

onProgressUpdate:在調用了publishProgress之後被UI線程調用。執行的時間無法估計。
當後台任務在執行的過程中,這個方法用來在用戶界面顯示進度,比如:它可以用來顯示進度條的動畫或者是在文本上顯示log。

onPostExecute:後台任務執行完畢以後,被UI線程調用。後台線程的執行結果會作為一個參數被傳進來。

取消一個任務
在任何時候通過調用cancel(boolean)可以用來取消一個任務。調用這個方法以後,隨後調用isCancelled()都會返回true。
調用了這個方法以後,doInBackground(Object[])返回以後,onCancelled(Object)而不是onPostExecute(Object)會被執行。
確保一個任務盡快的取消掉,你應該盡可能多的重復在doInBackground(Object[])這個方法裡面檢查isCancelled()的返回值。

線程規則
為了讓這個類能正常工作,需要遵守下面一些規則:
AsyncTask必須要在主線程加載,在JELLY_BEAN(4.1)這個版本系統會自動做這個工作。
task實例必須是在UI線程創建的
必須在UI線程調用(execute)開始執行
不要手動的調用 onPreExecute(), onPostExecute, doInBackground, onProgressUpdate
一個task只被執行一次(如果嘗試執行第二次會拋異常)

內存可見性
AsyncTask保證所有的回調方法都是同步的,因此,以下的操作不用做額外的同步處理但是都是安全的。
在構造函數或者onPreExecute裡面設置成員變量,然後在doInBackground這裡面進行引用
在doInBackground設置成員變量,然後在onProgressUpdate和onPostExecute進行引用

執行的順序
當第一次引入的時候,AsyncTasks是在單個後台線程上執行任務的
從1.6開始,改為使用線程池,允許多任務並行執行
從3.0開始,任務又改為在單線程上執行,避免並行執行可能引起的錯誤
如果你真的想並行的執行任務,你可以使用THREAD_POOL_EXECUTOR,調用executeOnExecutor(java.util.concurrent.Executor, Object[])這個方法。
public final AsyncTask execute(Params... params) {
return executeOnExecutor(sDefaultExecutor
}

原文:
android.os.AsyncTask
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread
without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the
java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
An asynchronous task is defined by 3 generic types, called Params, Progress and Result,
and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Developer Guides
For more information about using tasks and threads, read the Processes and Threads developer guide.

Usage
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground),
and most often will override a second one (onPostExecute.)

Here is an example of subclassing:
private class DownloadFilesTask extends AsyncTask {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog(Downloaded + result + bytes);
}
}

Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);

AsyncTask's generic types
The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

private class MyTask extends AsyncTask { ... }

The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:

onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task,
for instance by showing a progress bar in the user interface.

doInBackground, invoked on the background thread immediately after onPreExecute() finishes executing.
This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step.
The result of the computation must be returned by this step and will be passed back to the last step.
This step can also use publishProgress to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate step.

onProgressUpdate, invoked on the UI thread after a call to publishProgress. The timing of the execution is undefined.
This method is used to display any form of progress in the user interface while the background computation is still executing.
For instance, it can be used to animate a progress bar or show logs in a text field.

onPostExecute, invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Cancelling a task
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true.
After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.
To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from
doInBackground(Object[]), if possible (inside a loop for instance.)

Threading rules
There are a few threading rules that must be followed for this class to work properly:

The AsyncTask class must be loaded on the UI thread. This is done automatically as of android.os.Build.VERSION_CODES.JELLY_BEAN.
The task instance must be created on the UI thread.
execute must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute, doInBackground, onProgressUpdate manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Memory observability
AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.

Set member fields in the constructor or onPreExecute, and refer to them in doInBackground.
Set member fields in doInBackground, and refer to them in onProgressUpdate and onPostExecute.

Order of execution
When first introduced, AsyncTasks were executed serially on a single background thread.
Starting with android.os.Build.VERSION_CODES.DONUT(1.6), this was changed to a pool of threads allowing multiple tasks to operate in parallel.
Starting with android.os.Build.VERSION_CODES.HONEYCOMB(3.0), tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

public final AsyncTask execute(Params... params) {
return executeOnExecutor(sDefaultExecutor
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved