【发布时间】:2016-07-31 10:23:35
【问题描述】:
正如文档所说,onCancelled(Object) 应该在以下时间被调用:
cancel(boolean) 被调用并且 doInBackground(Object[]) 已经完成。
在我的AsyncTask 中,我调用了this.cancel(true);,但从未调用过onCancelled(Object) 方法。
这里只贴相关代码。
MainActivity.java:
AsyncTask.Status asyncTaskStatus = new GetHtmlDocument(urlString).execute().getStatus();
异步任务:
private class GetHtmlDocument extends AsyncTask<String,Void,HtmlPage>
{
private String url;
/**
* Constructor.
*
* @param url Url to parse from in the web.
*/
public GetHtmlDocument(String url)
{
this.url = url;
}
@Override
protected void onPreExecute()
{
Log.d(MainActivity.ASYNC_TASK_TAG, "onPreExecute() called");
}
@Override
protected HtmlPage doInBackground(String... params)
{
//android.os.Debug.waitForDebugger();
Log.d(MainActivity.ASYNC_TASK_TAG, "doInBackground() called");
if (this.isCancelled())
{
return null;
}
else
{
HtmlPage htmlPage = new HtmlPage(getParsedDocument(this.url));
return htmlPage;
}
}
/**
* Runs on the UI thread after doInBackground().
* The specified result is the value returned by doInBackground().
* This method won't be invoked if the asynchronous task was cancelled.
*
* @param htmlPage
*/
@Override
protected void onPostExecute(HtmlPage htmlPage)
{
Log.d(MainActivity.ASYNC_TASK_TAG, "onPostExecute() called");
if (htmlPage.getHtmlDocument() != null)
{
this.cancel(true);
}
setHtmlPage(htmlPage);
}
/**
* 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.)
*
* @param htmlPage
*
*/
@Override
protected void onCancelled(HtmlPage htmlPage)
{
Log.d(MainActivity.ASYNC_TASK_TAG, "onCancelled() called");
}
}
我调试了应用程序,我确定this.cancel(true); 在AsyncTask onPostExecute() 方法中被调用。
【问题讨论】:
标签: java android multithreading android-studio android-asynctask