AsyncTask

来源:互联网 发布:淘宝王子是什么 编辑:程序博客网 时间:2024/05/01 15:18

原文地址:http://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask enables proper and easy use ofthe UI thread. This class allows to perform background operations and publishresults on the UI thread without having to manipulate threads and/or handlers.

AsyncTask(异步任务)能够让你合理、简单的使用UI线程。你能够在不操控线程或者Handler的情况下,执行一个后台操作并将结果发送给UI线程。

 

AsyncTask is designed to be a helper classaround Thread and Handler anddoes not constitute a generic threading framework. AsyncTasks should ideally beused for short operations (a few seconds at the most.) If you need to keepthreads running for long periods of time, it is highly recommended you use thevarious APIs provided by the java.util.concurrent pacakge suchas Executor, ThreadPoolExecutor and FutureTask.

AsyncTask被设计成 Thread 和Handler的一个帮助类,使用它可以不用构造一个普通的线程架构。AsyncTasks理想情况下应该是做一些简短的操作(最多几秒钟的操作)。如果需要保证线程持续运行一段较长时间,推荐你使用 java.util.concurrent 包提供的API例如:Executor, ThreadPoolExecutor 和 FutureTask。

 

An asynchronous task is defined by acomputation that runs on a background thread and whose result is published onthe 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.

一个“异步任务”被定义为一个运行于后台线程的运算并且会将结果发送给UI线程的操作。“异步任务”需要三个泛型( Params, Progress and Result)和四个步骤(onPreExecute, doInBackground, onProgressUpdate and onPostExecute)来完成。

 

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

要实现一个“异步任务”需要继承AsyncTask类。而这个子类必须覆写至少一个方法doInBackground(Params...),大多数情况下还需要覆写onPostExecute(Result)方法。

 

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);


Thethree types used by an asynchronous task are the following:

1.Params, the type of the parameters sentto the task upon execution.

2.Progress, the type of the progress unitspublished during the background computation.

3.Result, the type of the result of thebackground computation.

三个泛型:

1.Param,发送给正在运行的任务的参数的数据类型

2.Progress,后台计算中发布进度单位的数据类型

3.Result,后台计算结果的数据类型

 

Notall types are always used by an asynchronous task. To mark a type as unused,simply use the type Void:

并不是一个“异步任务”需要填写所有的泛型。哪个泛型不用,就简单的Void代替即可。

 

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

Whenan asynchronous task is executed, the task goes through 4 steps:

要执行一个“异步任务”,需要执行四步:

 

1.onPreExecute(),invoked on the UI thread immediately after the task is executed. This step isnormally used to setup the task, for instance by showing a progress bar in theuser interface.

该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条。 

 

2.doInBackground(Params...),invoked on the background thread immediately after onPreExecute() finishesexecuting. This step is used to perform background computation that can take along time. The parameters of the asynchronous task are passed to this step. Theresult of the computation must be returned by this step and will be passed backto the last step. This step can also use publishProgress(Progress...) topublish one or more units of progress. These values are published on the UIthread, in the onProgressUpdate(Progress...) step.

将在onPreExecute()方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些很耗时的后台计算工作。这一步,异步任务的参数会传进来。可以调用publishProgress(Progress...) 方法来更新实时的任务进度。这些值将在onProgressUpdate(Progress...) 中显示

 

3.onProgressUpdate(Progress...),invoked on the UI thread after a call to publishProgress(Progress...).The timing of the execution is undefined. This method is used to display anyform of progress in the user interface while the background computation isstill executing. For instance, it can be used to animate a progress bar or showlogs in a text field.

在 publishProgress(Progress...)方法被调用后。任务执行的时间是不确定。UI thread将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。

 

4.onPostExecute(Result),invoked on the UI thread after the background computation finishes. The resultof the background computation is passed to this step as a parameter.

在后台计算运行完之后,onPostExecute(Result)方法将被UI thread调用,后台的计算结果将通过该方法传递到UI thread.

 

Cancellinga task

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

通过调用cancel(boolean)方法,一个任务可以在任何时间停止。调用这个方法会引起isCancelled() 返回一个true。在这个方法调用后, onCancelled(Object)方法会代替onPostExecute(Object),在doInBackground(Object[])方法返回之后运行。为了确保一个任务可以尽快的结束,你必须尽可能的时常检查isCancelled() 的返回值。


Threading rules

There are a few threading rules that mustbe followed for this class to work properly:

1.The AsyncTask class must be loaded on theUI thread. This is done automatically as of JELLY_BEAN.

2.The task instance must be created on theUI thread.

3execute(Params...) mustbe invoked on the UI thread.

4.Do not

call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.

5.The task can be executed only once (anexception will be thrown if a second execution is attempted.)

使用AsyncTask类,以下是几条必须遵守的准则:

1.AsyncTask的类必须在UI线程中载入

2.Task的实例必须在UI thread中创建

3.execute方法必须在UI thread中调用

4.不要手动的调用 

onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) 这几个方法

5.该task只能被执行一次,多次调用时将会出现异常