【发布时间】:2011-07-10 13:20:06
【问题描述】:
根据AsyncTask.cancel method 的 Android 参考,明确定义了 onCancelled() 和 doInBackground() 之间的时间:
调用此方法将导致在 doInBackground(Object[]) 返回后在 UI 线程上调用 onCancelled(Object)。调用此方法保证永远不会调用 onPostExecute(Object)
但是,查看我的 logcat,我可以看到 onCancelled() 方法在 doInBackground() 方法返回之前执行。
07-10 12:38:57.000: VERBOSE/AsyncTask(7473): doInBackground entered
07-10 12:38:57.000: VERBOSE/AsyncTask(7473): AsyncTask attempting to take the lock
07-10 12:38:57.000: VERBOSE/AsyncTask(7473): AsyncTask got the lock
07-10 12:38:57.420: VERBOSE/AsyncTask(7473): Start Item[0].state = 0
07-10 12:38:57.933: VERBOSE/AsyncTask(7473): onProgressUpdate entered
07-10 12:38:57.940: VERBOSE/AsyncTask(7473): onProgressUpdate exited
07-10 12:38:58.320: VERBOSE/(7473): onCancelListener cancelling AsyncTask
07-10 12:38:58.400: VERBOSE/AsyncTask(7473): onCancelled entered
07-10 12:38:58.400: VERBOSE/AsyncTask(7473): onCancelled exited
07-10 12:38:58.560: VERBOSE/AsyncTask(7473): Started checking file URL
07-10 12:38:58.601: VERBOSE/FileHost(7473): checkFile entered
07-10 12:38:58.641: VERBOSE/FileHost(7473): checkFile checking URI
07-10 12:38:58.691: DEBUG/dalvikvm(7473): threadid=19 wakeup: interrupted
07-10 12:38:58.710: VERBOSE/AsyncTask(7473): AsyncTask released the lock
07-10 12:38:58.710: VERBOSE/AsyncTask(7473): doInBackground exited
使用调试器并在 onCancelled() 方法和 doInBackground() 方法结束处设置断点,我还可以看到 onCancelled() 在 doInBackground() 结束之前被调用。
我是否在 AsyncTask 中错误编码了某些内容,从而导致 Android 参考和我的应用程序行为之间的行为差异?
为 Gallal 添加了一些代码:
@Gallal,Activity 包含这段代码。
private class OnCancelListener implements AddUrlDialog.CancelListener {
@Override
public void cancel() {
if (addUrlInProgress == true) {
addUrlInProgress = false;
Log.v(TAG, "onCancelListener cancelling AsyncTask");
addUrlControl.stopUpdates(true);
AddUrlDialog.dismiss();
}
}
}
AsyncTask.cancel 在 addUrlControl.stopUpdates() 方法中被调用。
public void stopUpdates(boolean cleanupLists) {
if (asyncTaskExited != true) {
cancelRequest = true;
addUrlAsyncTask.cancel(true);
//TEST httpRequest.abort(); // Also sends an abort to the HTTP request
}
}
AsyncTask doInBackground 方法如下所示。
@Override
protected Void doInBackground(Void... v) {
Log.v(TAG, "doInBackground entered");
netConn = addUrlControl.myApp.getNetConn();
client = netConn.getHttpClient();
try {
doInBackgroundBody();
} catch (Throwable t) {
Log.e(TAG, "doInBackgroundBody threw an exception: ", t);
} finally {
addUrlControl.myApp.releaseNetConn();
}
Log.v(TAG, "doInBackground exited");
return null;
}
【问题讨论】:
-
日志消息的顺序总是一样的吗?您正在从不同的线程进行日志记录,因此 logcat 中的消息顺序可能会在应用程序运行之间发生变化并出现错误。
-
@Herrrmann,日志消息的顺序是一样的。在调试器中放置断点表明 onCancelled() 在 doInBackground() 返回结束之前被调用。
标签: android