关于AsyncTask中的cancel方法

本文详细介绍了如何使用AsyncTask的cancel方法来取消正在执行的任务。通过调用cancel方法,可以根据需求选择是否中断正在运行的任务线程,并且在任务被取消后会调用onCancelled方法而非onPostExecute方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里总结一下:

  文档地址

  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 去进行判断。

  **注意,我们的oncancelled和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已经加载完成,或者 已经取消过一次,或者是其他情况



转自:http://www.educity.cn/develop/1378229.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值