现在的位置: 首页 > 综合 > 正文

Android-AsyncTask的javadoc文档

2013年01月24日 ⁄ 综合 ⁄ 共 7729字 ⁄ 字号 评论关闭

android.os.AsyncTask<Params, Progress, Result>
AsyncTask允许简单适当的使用UI线程。这个类允许执行后台操作,然后把结果发布到UI线程,同时又免去了手动的操作线程或者是handler。

AsyncTask被设计成是线程和Handler的帮助类,并没有构建一个通用的线程框架。
AsyncTask理想的使用场景是用于执行时间短的操作(最多几秒)
如果你需要让线程长时间执行,强烈推荐使用java.util.concurrent包下面提供的api,比如: Executor, ThreadPoolExecutor和FutureTask。

一个异步的任务指的是运行在后台线程上的操作,它的执行结果会发布到UI线程上。
一个异步任务是由3个泛型类型(Params, Progress和Result)和4个执行步骤来表示的(onPreExecute, doInBackground, onProgressUpdate和onPostExecute)。

开发者指南
想获取更多关于异步任务和线程的信息,可以参考:http://developer.android.com/guide/components/processes-and-threads.html这个文档

使用
必须是AsyncTask的子类才可以使用,子类需要覆盖至少一个方法(doInBackground),大多数都会覆盖第二个(onPostExecute)方法。

这是一个例子:
 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     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<Void, Void, Void> { ... }

四个步骤
异步任务在执行的时候,会经历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<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor
}

原文:
android.os.AsyncTask<Params, Progress, Result>
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<URL, Integer, Long> {
     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<Void, Void, Void> { ... }
 
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<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor
}

抱歉!评论已关闭.