AsyncTask

来源:互联网 发布:java读取exe文件 编辑:程序博客网 时间:2024/05/01 12:52

由于最近感觉到英语颇为重要,所以想通过翻译一些英文API来练一下阅读英文文档的能力

public abstract class

AsyncTask

extends Object
java.lang.Object   android.os.AsyncTask<Params, Progress, Result>
由上可知,AsyncTask是抽象类,继承于Object类

Class Overview

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.

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, calledParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

类概述

AsyncTask能够适当地和容易地用于UI线程。这个类不用去操作线程或者handler就可以执行后台操作并且返回给UI线程。异步任务是定义在后台线程,执行结果公布在UI线程的一个计算。异步任务是被定义为3个泛化类型,分别是:Params,Progress和Result和4个步骤,分别是:onPreExecute,doInBackgroud,onProgressUpdate和onPostExecute。

Usage

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

Here is an example of subclassing:

用法

AsyncTask必须由子类去使用。子类至少应该重写doInBackground(Params...)这个方法,大多数情况下还会去重写onPostExecute(Result)这个方法。下面是AsyncTask子类的一个例子。

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

  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. 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> { ... }
异步的泛化类型
异步任务的三种类型如下:
1、Params,启动任务执行时的输入参数
2、Progress后台任务执行的进度
3、Result后台任务计算返回的结果
在一个异步任务中,不是所有的类型都要被使用。要标记一个类型不被使用,可以简单地用类型void

The 4 steps

When an 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 is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), 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(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  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 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.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
当一个异步任务被执行时,这个任务将按以下4个步骤执行:
1、当异步任务开始执行,onPreExecute()就会在UI线程立即被调用。这个步骤通常用来设置任务,例如在用户界面上显示一条进度条。
2、当onPreExecute()执行完毕后就会立即调用doInBackground(Params ...)方法,该方法是在后台线程被调用的。这个步骤用来执行需要花费很长一段时间的后台计算。异步任务的参数传送给这步。执行结果必须从这步返回,并且会传递给最后一步(即onPostExecute的result参数,如上面API自带例子中doInBackground的返回参数类型和onPostExecute的接受参数类型都是Long型可进一步断定该结论)。在执行当中,可以调用publishProgress(Progress ...)来返回一个值。这个值会被UI线程里的onProgressUpdate(Progress ...)接收并处理。
3、当调用publishProgress(Progress ...)时,onProgressUpdate(Progress ...)会在UI线程被调用。执行时间是不确定的。这个方法可以在后台任务执行时以任何形式在UI显示进度。例如,它可以用来推进一个进度条或者在文本域中显示记录。
4、当后台计算任务完成后,OnPostExecute(Result)会在UI线程被调用。后台计算结果会作为一个参数传送给这一步。

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

取消一个任务
通过调用cancel(boolean),一个任务可以在任何时刻被取消掉。调用这个方法会引起随后isCanceled()这个方法返回true。如果cancel(boolean)被调用,那么当doInBackground返回后,并不会去调用onPostExecute,而是调用onCanceled方法。为了确保一个任务尽快被取消,你应该经常检查isCancelled()这个方法的返回值,如果可以的话,在一个循环中检查。(即写一个循环来判断isCancelled的返回值,如果返回true,即表明后台任务已成功取消)

Threading rules

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

  • The task instance must be created on the UI thread.
  • execute(Params...) must be invoked on the UI thread.
  • Do not call onPreExecute()onPostExecute(Result)doInBackground(Params...)onProgressUpdate(Progress...) manually.
  • The task can be executed only once (an exception will be thrown if a second execution is attempted.)
线程规则
必须遵守一些线程的规则,这个类才能正确地工作
任务实例必须是在UI线程里创建的
execute必须在UI线程里调用
不要手动地去调用onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) 这几个方法
这个任务只能被执行一次(如果试图调用第二次将会跑出异常,有点类似于Thread,因为Thread一旦执行完毕,就不能重新start了)

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(Params...).
  • Set member fields in doInBackground(Params...), and refer to them in onProgressUpdate(Progress...) and onPostExecute(Result).
内存可观察性
AsynTask保证所有回调调用不用显示加synchronized也是线程安全的。
Nested ClassesenumAsyncTask.StatusIndicates the current status of the task.  内部类表示当前任务的状态 Public ConstructorsAsyncTask()
Creates a new asynchronous task.
构造方法创建一个异步对象,在UI线程中调用

Public Methods

public final boolean cancel (boolean mayInterruptIfRunning)

Since: API Level 3

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked. After invoking this method, you should check the value returned by isCancelled() periodically from doInBackground(Object[]) to finish the task as early as possible.

Parameters
mayInterruptIfRunningtrue if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.
Returns
  • false if the task could not be cancelled, typically because it has already completed normally; true otherwise
See Also
  • isCancelled()
  • onCancelled(Object)
公有方法
fianal表示该方法不能被子类重写
尝试取消任务的执行。如果任务已经完成后被取消,或者由于其他原因不能被取消,这个操作将失败。如果调用成功,而且这个任务还没有开始执行,那么这个任务将永远不会被执行。如果这个任务已经开始执行了,且mayInterruptIfRunning为true,那么执行这个任务的线程可以被试图中断。
参数
mayInterruptIfRunning 如果是true,正在执行的线程将被中断,如果为false,将允许正在执行的线程执行完毕
返回
如果任务不能被取消将返回false,典型的原因是因为任务已经完成后正常结束了。true则能够正常结束。


原创粉丝点击