码迷,mamicode.com
首页 > 其他好文 > 详细

AsyncTask源码翻译

时间:2015-07-08 14:42:53      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

前言:
/**

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的正确实现,易于使用的用户界面线程。此类允许执行后台操作并把结果发布在UI线程上(主线程)而且使用handler.
*

AsyncTask is designed to be a helper class around {@link Thread} and {@link 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 package such as {@link Executor},{@link ThreadPoolExecutor} and {@link FutureTask}.


译文:异步任务帮助类的设计是围绕着线程和Handler的,但是并不构成通用线程的框架,异步任务应该用于很短的时间操作(几秒钟),如果你需要保持线程运行很长一段时间的话,你需要查看其他的各种api.

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, calledonPreExecute, doInBackground, onProgressUpdate and onPostExecute.


译文:一个异步任务由在后台线程运行的计算,其结果传给UI线程上。一个异步任务由3泛型类型定义,名为PARAMS,Progress和Result,和4个步骤,名为 onPreExecute(准备阶段),doInBackground(执行阶段),onProgressUpdate(进度更新阶段)和 onPostExecute(执行完成阶段)。
*

*

Developer Guides


*

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


*

译文:特别参考开发者手册,更多关于任务和线程的请阅读{@docRoot}guide/topics/fundamentals/processes-and-threads.html进程和线程开发者引导。

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

Here is an example of subclassing:

 
* 译文:异步任务必须被子类继承并且必须实现至少一种方法(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");
}
}

Once created, a task is executed very simply:

 new DownloadFilesTask().execute(url1, url2, url3); 
*

译文:一次被创建,一个任务将会执行的非常简单(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. 译文:Params,是执行任务时发送的参数类型。
  3. Progress, the type of the progress units published during the background computation.
  4. 译文:Progress,是后台计算过程中的进度单元类型。
  5. Result, the type of the result of the background computation.

译文:Result,是后台线程计算得到结果的类型。

Not all types are always used by an asynchronous task. To mark a type as unused,simply use the type {@link Void}
译文:不是所有类型都被一个异步任务使用。要标记为未使用的类型,只需使用该类型
* private class MyTask extends AsyncTask<Void, Void, Void> { … }
*

The 4 steps


*

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

译文:当一个异步任务被执行时,任务就通过4个步骤来完成
*
  • {@link #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.
  • 译文:onPreExecute()在任务执行前,在用户界面上调用线程。这一步通常用于设置任务,例如通过在用户界面显示一个进度条。
    *
  • {@link #doInBackground}, invoked on the background thread immediately after {@link #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 {@link #publishProgress} to publish one or more units of progress. These values are published on the UI thread, in the {@link #onProgressUpdate} step.
  • 译文:在onPreExecute()执行完后在后台线程上调用,这一步是用来执行后台耗时操作,可能耗费很长时间。异步任务的完成的结果必须返回在这一步,并将被传递到最后一步。这一步还可以使用publishProgress()这个方法吧进度传送给UI线程在,onProgressUpdate()这一步
  • {@link #onProgressUpdate}, invoked on the UI thread after a call to {@link #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.
  • 译文:onProgressUpdate(),被UI线程调用在publishProgress这个方法之后,执行的时间是不确定的,这个方法被用来展示进度信息给用户,而后台任然在执行,建议实例它可用于在文本字段中动画一个进度条或显示日志。
  • {@link #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.

  • 译文:调用UI线程完成之后,后台结果被传递到这一步。

    Cancelling a task

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


    译文:一个任务能被执行取消在任意一时刻,执行这个方法将随后会调用isCancelled()这个方法返回true,之后执行onCancelled(Object),而不是onPostExecute(Object),之后将会执行doInBackground(Object[])} 的返回,确保任务尽可能的快速被取消,你应该总是检查isCancelled()的返回值定期doInBackground(Object[])如果可能的话。

    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 {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.
    • The task instance must be created on the UI thread.
    • {@link #execute} must be invoked on the UI thread.
    • Do not call {@link #onPreExecute()}, {@link #onPostExecute}, {@link #doInBackground}, {@link #onProgressUpdate} manually.
    • The task can be executed only once (an exception will be thrown if a second execution is attempted.)

    译文:AsyncTask必须加载在UI线程。这是android.os.Build.VERSION_CODES自动完成的,异步任务的实例必须创建在UI线程,不能手动调用onPreExecute(),onPostExecute,doInBackground, onProgressUpdate。

    Memory observability

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


    译文:AsyncTask的保证所有回调调用以这样的方式,下面的操作都没有明确的同步安全同步。

    • Set member fields in the constructor or {@link #onPreExecute}, and refer to them in {@link #doInBackground}.
    • Set member fields in {@link #doInBackground}, and refer to them in {@link #onProgressUpdate} and {@link #onPostExecute}.

    译文:设置属性在构造函数里,或者onPreExecute(),并引用他们在doInBackground,设置成员属性在doInBackground,引用他们在onProgressUpdate和onPostExecute。

    Order of execution

    When first introduced, AsyncTasks were executed serially on a single background thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, 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{@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with
    {@link #THREAD_POOL_EXECUTOR}.


    译文:当第一次推出,AsyncTasks是在一个后台线程执行,这被改为允许线程多任务并行操作的线程池允许多任务操作。任务是在单个线程中执行,以避免因并行执行常见的应用程序错误。如果你真正想要并行执行,你可以调java.util.concurrent.Executor类。

    AsyncTask源码翻译

    标签:

    原文地址:http://blog.csdn.net/u013200864/article/details/46801887

    (0)
    (0)
       
    举报
    评论 一句话评论(0
    登录后才能评论!
    © 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
    迷上了代码!