在AsyncTask中覆盖pre/post execute并调用super.onPre/PostExecute

5
在重写AsyncTask的onPreExecute方法时,是否必须调用super.onPreExecute? AsyncTask.onPreExecute和其他方法实际上是做什么的? 对于onPostExecute和onCancelled也有同样的问题。
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;
}
2个回答

11
不需要调用super。这是源代码
可以看到,默认实现什么都不做。
/**
* 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) {
}

还是调用super会不会是一个好的实践,因为未来可能会更新AsyncTask呢?现在没有什么问题,但如果他们改变了呢... - Daniel

1

不需要强制重写方法 onPreExecute 和 onPostExecute。

onPreExecutedoInBackground进程开始之前调用。我们可以在此方法中添加代码,在任何事情开始工作之前完成必须要做的工作。

doInBackground 在后台工作,因此在此方法中可以进行任何我们想要在后台执行的操作,例如调用web服务等。但是请注意,不要在此方法中设置UI小部件,否则会出现异常。

onPostExecutedoInBackground完成后调用,在此方法中,我们可以设置UI小部件和其他代码以在Web服务调用完成后进行设置。

OnCancelled 任务可以随时通过调用cancel(boolean)来取消。调用此方法将导致后续对isCancelled()的调用返回true。

检查this链接。希望这能帮助到您。


我在询问基类的实现,但无论如何感谢您花费时间。 - Mar Bar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接