频道栏目
首页 > 程序开发 > 移动开发 > Android > 正文
Android基础 -- AsyncTask介绍和使用
2016-05-10 09:12:39         来源:Feathers的个人笔记  
收藏   我要投稿

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

为了保持良好的博客习惯,我还是把这篇笔记贴了出来,虽然他是翻译的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 aroundThreadandHandlerand 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 thejava.util.concurrentpackage such asExecutor,ThreadPoolExecutorandFutureTask.

这一段大概说,这个类只是个为了方便使用thread和handler的辅助类,不能构成一个框架,他只能进行断的线程操作。要想进行长的线程操作,还要去java.util.concurrent中找Executor,ThreadPoolExecutorandFutureTask(话说这三个是什么鬼)

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(泛型), calledParams,ProgressandResult, and 4 steps, calledonPreExecute,doInBackground,onProgressUpdateandonPostExecute.

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

一个AsynTask的定义通过三种泛型calledParams,ProgressandResultonPreExecute,doInBackground,onProgressUpdateandonPostExecute四个步骤

 

Developer Guides

For more information about using tasks and threads, read theProcesses and Threadsdeveloper 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 { //注意继承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.  
  14. protected void onProgressUpdate(Integer... progress) {
  15. setProgressPercent(progress[0]);
  16. }
  17.  
  18. protected void onPostExecute(Long result) {
  19. showDialog("Downloaded " + result + " bytes");
  20. }
  21. }

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:

Params, the type of the parameters sent to the task upon execution. 执行任务时所需要的参数的泛型Progress, the type of the progress units published during the background computation. 执行任务时,后台运行的进度的泛型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 typeVoid:

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



 

The 4 steps(三个泛型睾丸,就是四个步骤)


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

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线程上。这一步通常用于设置任务,比如通过用户界面显示一个进度条

doInBackground(Params...), invoked on the background thread immediately afteronPreExecute()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 usepublishProgress(Progress...)to publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdate(Progress...)step.

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

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

onProgressUpdate(Progress...), invoked on the UI thread after a call topublishProgress(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,同时后台线程仍在运行。

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

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 invokingcancel(boolean).可以在任何时间内随时取消该任务 Invoking this method will cause subsequent(随后) calls toisCancelled()to return true. 调用这个方法后,isCancelled()方法将会返回true(这不是废话吗)。

After invoking this method,onCancelled(Object), instead ofonPostExecute(Object)will be invoked afterdoInBackground(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 ofisCancelled()periodically fromdoInBackground(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(正常工作):

private class MyTask extends AsyncTask { ... }

The AsyncTask class must be loaded on the UI thread. This is done automatically as ofJELLY_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 callonPreExecute(),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(尝试).) 该任务只能被执行一次,第二次尝试执行会有抛出异常

 

 

 

点击复制链接 与好友分享!回本站首页
相关TAG标签 基础
上一篇:Android系列之广播
下一篇:Demo3悬浮的按钮:FloatActionButton(Design Support Lib)
相关文章
图文推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站