关于AsyncTask中的cancel方法

移动开发 Android
在adroid 应用程序中,我们经常会用到异步加载。 所以我们也要知道如何取消加载。 比如,当用户点击图片加载时,如果用户可能需要取消加载。 怎样取消呢 我去百度找了很久也没找到 。于是就自己去API文档中查找。

在这里总结一下:

文档地址

 

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)去取消这个加载任务,调用这个方法会间接调用 iscancelled 并且返回true 。

 

当调用cancel()后,在doInBackground()return后 我们将会调用onCancelled(Object) 不在调用onPostExecute(Object)

 

为了保证任务更快取消掉,你应该在doInBackground()周期性的检查iscancelled 去进行判断。

**注意,我们的oncancel和onPostExecute一样,都是在UI线程中执行。。。所以当我们想要取消之后,有些界面变化 我们可以在oncancel里面改变UI.

关于cancel方法

 

public final boolean cancel (boolean mayInterruptIfRunning)

 

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.

 

某些情况下,我们调用cancel(true)可能就会失效

 

比如 :task已经加载完成,或者 已经取消过一次,或者是其他情况

责任编辑:张叶青 来源: eoe Android开发者社区
相关推荐

2010-12-01 14:34:59

AsyncTask异步处理任务Android

2015-10-23 15:22:16

AsyncTask基础Android

2011-12-02 14:00:21

JavaOOM

2019-11-07 23:48:12

shell脚本getopts

2011-08-08 14:07:49

iPhone开发 字体

2011-08-16 18:56:11

iPhone开发Three20

2011-08-15 09:58:25

iPhoneXib文件UITableView

2014-06-05 15:13:21

BGP

2009-12-03 19:06:01

软路由设置

2011-08-19 10:35:19

iPhone应用Three20

2020-03-02 00:32:08

Python列表for循环

2011-08-23 15:57:21

Lua元表元方法

2009-12-08 10:01:12

2012-05-14 10:18:54

jQuery

2011-08-24 14:47:55

LUA文本编辑器

2009-11-23 12:50:26

ADSL宽带路由器设置

2011-06-16 11:01:56

PHP继承

2012-11-20 12:38:29

2009-06-17 16:01:28

2009-11-26 16:54:01

无线网卡安装
点赞
收藏

51CTO技术栈公众号