關(guān)于AsyncTask中的cancel方法
在這里總結(jié)一下:
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.)
這是話意思是
我們可以隨時(shí)調(diào)用 cancel(boolean)去取消這個(gè)加載任務(wù),調(diào)用這個(gè)方法會(huì)間接調(diào)用 iscancelled 并且返回true 。
當(dāng)調(diào)用cancel()后,在doInBackground()return后 我們將會(huì)調(diào)用onCancelled(Object) 不在調(diào)用onPostExecute(Object)
為了保證任務(wù)更快取消掉,你應(yīng)該在doInBackground()周期性的檢查iscancelled 去進(jìn)行判斷。
**注意,我們的oncancel和onPostExecute一樣,都是在UI線程中執(zhí)行。。。所以當(dāng)我們想要取消之后,有些界面變化 我們可以在oncancel里面改變UI.
關(guān)于cancel方法
public final boolean cancel (boolean mayInterruptIfRunning)
某些情況下,我們調(diào)用cancel(true)可能就會(huì)失效
比如 :task已經(jīng)加載完成,或者 已經(jīng)取消過一次,或者是其他情況