關於cancelAllTasks疑問
1.task.cancel(false),記得初級課程時,是將它標註成true,再由isCanceled判斷是否要繼續
2,呼叫cancel的方法,就能讓task停止嗎?只是標註該task要取消,然後在task中去檢查,當isCanceled為true時終止目前的工作,讓task能提早結束
1.task.cancel(false),記得初級課程時,是將它標註成true,再由isCanceled判斷是否要繼續
2,呼叫cancel的方法,就能讓task停止嗎?只是標註該task要取消,然後在task中去檢查,當isCanceled為true時終止目前的工作,讓task能提早結束
2015-06-10
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结束,这个方法才能执行。不过需不需要重写这个方法完全看具体需求了。
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)
这是方法的文档,写的很清楚了。跟你说的差不多。
举报