關於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
舉報
2015-06-11
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結束,這個方法才能執行。不過需不需要重寫這個方法完全看具體需求了。
2015-06-11
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)
這是方法的文檔,寫的很清楚了。跟你說的差不多。