Android基础 -- AsyncTask介绍和使用

2016年5月9日 可以迷茫,但不可以放弃

好久好久没写博客了,这一个多月的时间,自己的身体和心理状态对我来说都是差劲的。不是不想写博客,而是实在写不出有观点的新颖的东西,面临将要工作这一现实,内心还是有一丢丢担心和忧虑的。

为了保持良好的博客习惯,我还是把这篇笔记贴了出来,虽然他是翻译的google的api,但是,希望这篇文章可以帮到和我一样英语不好的人,让我们一同进步。


AsynTask

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.

一种异步处理机制,他不需要操作线程或者使用handler就可以控制UI线程

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 package such asExecutorThreadPoolExecutor and FutureTask.

这一段大概说,这个类只是个为了方便使用thread和handler的辅助类,不能构成一个框架,他只能进行断的线程操作。要想进行长的线程操作,还要去java.util.concurrent中找ExecutorThreadPoolExecutor 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(泛型), calledParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

讲了什么是异步任务,好吧是在翻译不通顺,只能自己写一下了:就是在非UI线程上进行运算,在然后将结果更新在UI线程上

一个AsynTask的定义通过三种泛型calledParamsProgress and Result 和 onPreExecutedoInBackgroundonProgressUpdate 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(Params...)), and most often will override a second one (onPostExecute(Result).)

该类是抽象类,使用必须子类继承,并至少覆盖一个方法doInBackground(Params...)而且通常重写onPostExecute(Result)方法


栗子:

 
 
  1. private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {  //注意继承asynctask要写泛型
  2.     protected Long doInBackground(URL... urls) {
  3.         int count = urls.length;
  4.         long totalSize = 0;
  5.         for (int i = 0; i < count; i++) {
  6.             totalSize += Downloader.downloadFile(urls[i]);
  7.             publishProgress((int) ((i / (float) count) * 100));
  8.             // Escape early if cancel() is called  如果cancel被调用  异步任务将会提早退出
  9.             if (isCancelled()) break;
  10.         }
  11.         return totalSize;
  12.     }
  13.     protected void onProgressUpdate(Integer... progress) {
  14.         setProgressPercent(progress[0]);
  15.     }
  16.     protected void onPostExecute(Long result) {
  17.         showDialog("Downloaded " + result + " bytes");
  18.     }
  19. }

Once created, a task is executed very simply:

这里是启动任务的方法:

 
 
  1. 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:

这三个泛型不一定都用的上,不用的用void就可以了

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

The 4 steps(四个步骤)


When an asynchronous task is executed, the task goes through 4 steps:  执行一个异步任务  要四部

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

    在执行异步任务前,调用该方法,注意:该方法运行在UI线程上。这一步通常用于设置任务,比如通过用户界面显示一个进度条

  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.

    在执行完onPreExecute方法后,立即调用此方法(在非UI线程中),此步骤可以用来进行后台运算,可能会需要较长的时间。前面的参数就是要传给他的,他接受参数进行处理后,返回的就是Result,不信你看他的返回值。而且他必须返回,然后再把这个返回值传给最后一步onPostExecute(Result)

    也可以在这个方法中调用publishProgress(Progress...)方法来改变进度。然后用第三步可以更新这些值到UI线程。

  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.

    在调用publishProgress(Progress...)之后在主线程中调用该方法。他的执行时间没有定义,该方法用于向用户显示progress,同时后台线程仍在运行。

    例如,他可以用来动态的更新进度条或日志

  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.

    执行请求。在后台运算完成后调用了用户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. 调用这个方法后,isCancelled()方法将会返回true(这不是废话吗)。 

After invoking this method,onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. 

调用该方法后,在doInBackground(Object[])方法返回结果后,将不会调用onPostExecute(Object)方法接受Result,而是调用onCancelled(Object)方法接受Result。(这里要等到doInBackground(Object[])方法结束后才能正是取消任务,所以需要使用isCancelled()在doInBackGround中判断)

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

为了确保任务可以尽快的取消,如果可以的话,你应该在doInBackground(Object[]中使用isCancelled()检查一下任务是否被取消了



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 JELLY_BEAN.  这个类必须在UI线程上加载
  • The task instance must be created on the UI thread.  task实例也必须在UI线程中创建
  • execute(Params...) must be invoked on the UI thread. execute()也必须在UI线程上
  • Do not call onPreExecute()onPostExecute(Result)doInBackground(Params...)onProgressUpdate(Progress...) manually.这几个方法不能手动调用,就像onCreate一样
  • The task can be executed only once (an exception will be thrown if a second execution is attempted(尝试).) 该任务只能被执行一次,第二次尝试执行会有抛出异常




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值