AsyncTask(一)

 AsyncTask<params,Progress,Result>

1Class Overview

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.

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

译文:AsyncTask能够正确容易的使用UI线程。这个类进行后台操作和在不用操作线程和Handler的情况下,发布结果给UI线程。

一个异步任务,被运行在后台线程的计算所定义,并且这个计算表的结果被发布到UI线程。

一个异步任务可以通过三个泛型类型和4个方法来定义。这三个泛型类型是Params\Progress\Result;四个方法是:onPreExecute\doInBackground\onProgressUpdateonPostExecute

2Usage

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

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));
         }
         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类来实现,子类至少应该重写doInBackground方法,通常情况下,经常重写onPostExecute方法。

3AsyncTask'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 atype as unused, simply use the type Void:

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

译文:异步任务使用的类型情况如下:

1、      Params:当执行的时候,发送给任务的参数类型

2、      Progress:在后台运算期间,被发布的进程单元的类型

3、      Result:后台运算的结果的类型

但是并不是所有的类型都是异步任务所必须的,如果某个类型是不需要的话,就把它设置成Void

4The 4 steps

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

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线程中运行,这一步一般被用来设置任务,比如说在用户界面弹出进度条

2.  doInBackground(Params...),invoked on the background thread immediately after onPreExecute()finishes executing. This step is used to perform background computation thatcan take a long time. The parameters of the asynchronous task are passed tothis step. The result of the computation must be returned by this step and willbe 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 UIthread, in the onProgressUpdate(Progress...)step.

译文:当onPreExecute方法执行完以后,在后台线程中执行这个方法。这一步一般用来进行后台运算,这种运算可能耗费一些时间。异步任务的参数会被传到这个方法中。运算结果必须被这个方法返回,并且运算结果会被传到最后一步。这个方法也可以调用publishProgress来发布一个或者多个进程单元。这些值会被发布给UI线程,在onProgressUpdate执行期间。

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之后,在UI线程中调用这个方法。

这个方法执行的时间是不确定的。这个方法被用来在用户界面上面显示任何形式的进度,当后天运算还在进行的时候。比如,它可以在一个文本域中显示logs和进度条。

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.

这个方法当后台运算结束后,在UI线程中运行。后台运算的结果被封装成一个参数传递给这个方法。

5Cancelling 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 shouldalways check the return value of isCancelled()periodically from doInBackground(Object[]),if possible (inside a loop for instance.)

译文:通过调用cancel方法,可以随时取消一个任务。调用这个方法的时候,会调用isCanceled方法,而这个方法的返回值是true。在调用了这个方法后,onCanceled方法将会在doInBackground返回后调用,而没有调用onPostExecute。为了确保任务被尽快的取消了,你应该在周期性的检查isCancelled方法的返回值,从doInBackground,如果可能的话

 

6Threading rules

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

·        The task instance must becreated 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 onlyonce (an exception will be thrown if a second execution is attempted.)

译文:为了正常让这个类工作,我们应当遵守以下的线程规则:

1、      任务实例必须在UI线程中创建

2、      Execute方法必须在线程中被调用

3、      onPreExecute(),onPostExecute(Result),doInBackground(Params...),onProgressUpdate(Progress...)这几个方法不能手动掉,应该让系统调用

4、      这个任务只能被执行一次,如果调用两次的话,会抛异常

7Memory observability

AsyncTask guarantees that all callback calls are synchronized insuch a way that the following operations are safe without explicitsynchronizations.

·        Set member fields in theconstructor 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).

译文:异步任务确保了任何回调方法的调用是同步执行的????

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值