2014-02-11 27 views
3

當在AsyncTask中重寫onPreExecute時,是否必須調用super.onPreExecute? AsyncTask.onPreExecute和其他方法實際上做了什麼? 爲onPostExecute同樣的問題,onCancelled覆蓋AsyncTask中的pre/post執行並調用super.onPre/PostExecute

public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> 
{ 

@Override 
protected void onCancelled(Boolean result) { 

    super.onCancelled(result); //<-DO I HAVE TO? 

      //My onCancelled code below 


} 

@Override 
protected void onPostExecute(Boolean result) { 

    super.onPostExecute(result); //<-DO I HAVE TO? 

      //My onPostExecute code below 
} 

@Override 
protected void onPreExecute() { 

    super.onPreExecute(); //<-DO I HAVE TO? 

      //My onPreExecute code below 

} 

@Override 
protected Boolean doInBackground(Void... params) { 

    return null; 
} 

回答

8

不,你不需要調用super。這裏是source

正如你所看到的,默認實現什麼都不做。

/** 
* Runs on the UI thread before {@link #doInBackground}. 
* 
* @see #onPostExecute 
* @see #doInBackground 
*/ 
protected void onPreExecute() { 
} 

/** 
* <p>Runs on the UI thread after {@link #doInBackground}. The 
* specified result is the value returned by {@link #doInBackground}.</p> 
* 
* <p>This method won't be invoked if the task was cancelled.</p> 
* 
* @param result The result of the operation computed by {@link #doInBackground}. 
* 
* @see #onPreExecute 
* @see #doInBackground 
* @see #onCancelled(Object) 
*/ 
@SuppressWarnings({"UnusedDeclaration"}) 
protected void onPostExecute(Result result) { 
} 
+0

優秀。並感謝您的源代碼鏈接。 –

+0

由於未來更新到'AsyncTask',是否仍然會調用'super'?現在什麼都沒有,但是如果他們改變了它...... – Daniel

2

不,我們不強制需要重寫方法 onPreExecute & onPostExecute。

onPreExecutedoInbackground過程開始,我們可以在這個方法中,我們有之前的任何事情開始工作doInbackground做添加代碼之前調用。

doInbackground 在後臺工作,所以在這個方法中做任何我們想在後臺做的事情,比如調用web服務和所有。但小心此方法不是在此方法中設置UI小部件。如果設置它將會出現異常。

onPostExecute完成後調用這個方法我們可以設置UI部件和其他代碼的Web服務調用完成後設置doInbackground &。

OnCancelled 任何時候都可以通過調用cancel(boolean)來取消任務。調用此方法將導致後續調用isCancelled()返回true。

檢查this鏈接。 希望這對你有所幫助。

+0

我在問基礎班的實施情況,不過謝謝你的時間。 –