为了账号安全,请及时绑定邮箱和手机立即绑定

關於cancelAllTasks疑問

1.task.cancel(false),記得初級課程時,是將它標註成true,再由isCanceled判斷是否要繼續

2,呼叫cancel的方法,就能讓task停止嗎?只是標註該task要取消,然後在task中去檢查,當isCanceled為true時終止目前的工作,讓task能提早結束

正在回答

2 回答

1,什么时候检查,这个就看你自己控制了,就跟结束一个线程一样,需要自己判断什么时候去检查flag。在你认为恰当的时机。你可以每隔一行检查一次。。。

2,onCancelled(Object)是AsyncTask的回调,带on的么。

Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns.

调用cancel方法会导致onCancelled(Object)执行,onCancelled在UI线程中,在doInBackgourn返回之后。

这是onCancelled的文档:

protected void onCancelled(Bitmap bitmap)

Description copied from class: AsyncTask 

Runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[]) has finished.

The default implementation simply invokes onCancelled() and ignores the result. If you write your own implementation, do not call super.onCancelled(result).

Overrides:

onCancelled in class AsyncTask

这个方法是在UI线程执行,cancel调用后并且doInBackground执行完成后执行。也就是说如果需要在task取消的时候做一些处理,那么就在这里进行。

是要设置检查点让doInBackground结束,这个方法才能执行。不过需不需要重写这个方法完全看具体需求了。

0 回复 有任何疑惑可以回复我~

public final boolean cancel (boolean mayInterruptIfRunning)

Added in API level 3


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.

Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked. After invoking this method, you should check the value returned by isCancelled() periodically from doInBackground(Object[]) to finish the task as early as possible.

Parameters

mayInterruptIfRunning

true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.

Returns

false if the task could not be cancelled, typically because it has already completed normally; true otherwise

See Also

isCancelled()

onCancelled(Object)

这是方法的文档,写的很清楚了。跟你说的差不多。

0 回复 有任何疑惑可以回复我~
#1

eric_0023 提问者

thanks 1 在doINBackground週期去檢查,多久檢查一次較恰當或有其它方法 2 onCancel是當task背景執行提早結束時會被呼叫,不過前題還是要設檢查點break工作來結束task,是這樣嗎? 如果是這樣 問題1 要怎麼解決
2015-06-11 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Android必学-异步加载
  • 参与学习       50627    人
  • 解答问题       311    个

了解Android中的异步加载处理方法,这是面试问的最多的知识点

进入课程

關於cancelAllTasks疑問

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信