我有一段使用AsyncTask运行后台的代码。代码类似于:
private class MyAsyncTask extends AsyncTask<Void, Void, Object> {
public MyAsyncTask() {
// Some init. code
}
@Override
protected Object doInBackground(Void... params) {
// Doing some long running task.
Log.v(TAG, "Finished everything. Returning ...");
return result;
}
@Override
protected void onCancelled(Object result) {
// Either way, run the next one in the line.
Log.v(TAG, "Task cancelled");
}
@Override
protected void onPostExecute(Object result) {
Log.v(TAG, "Task Completed.");
}
}
在Android 4上它运行得很好,但是当我在2.3上运行它(HTC Wildfire是我现在唯一的测试手机)时,不会调用onPostExecute。
我可以看到来自doInBackground
的最后一封邮件,但onCancelled
或onPostExecute
都没有收到任何邮件。还有其他人遇到过同样的问题吗?我发现这个link讨论了一个类似的问题,但是没有给出一个明确的解决方案(仅建议使用普通线程而不是AsyncTask
),也不是我正在寻找的。 p>
有什么建议吗?
干杯
好的,在花了一天时间阅读2.3和4中AsyncTask
,Handler
和Message
的代码之后,我现在有更多有关正在发生的事情的线索。
首先了解一下我的设计。我有一个单例类,它既可以在应用程序中使用,也可以在我的应用程序启动的一些服务中使用。因此,上面显示的AsyncTask
代码可以从活动中运行(假设通过活动访问单例),或者从服务运行(如果通过服务访问单例)。
现在在API 11+中,无论如何访问单例,onPostExecute
都被称为正常。在API 10及更低版本中,如果从活动访问单例,则onPostExecute
被调用就好了,但如果通过服务访问它,则不会调用onPostExecute
。
以下是有关卡住地点的详细信息。 2.3上的AsyncTask
有FutureTask
覆盖done
函数,可将Message
发送到其内部Handler
,如下所示:
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
Message message;
Result result = null;
try {
result = get();
} catch (final InterruptedException e) {
android.util.Log.w(AsyncTask.LOG_TAG, e);
} catch (final ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (final CancellationException e) {
message = AsyncTask.sHandler.obtainMessage(AsyncTask.MESSAGE_POST_CANCEL,
new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
message.sendToTarget();
return;
} catch (final Throwable t) {
throw new RuntimeException("An error occured while executing "
+ "doInBackground()", t);
}
message = AsyncTask.sHandler.obtainMessage(AsyncTask.MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(AsyncTask.this, result));
message.sendToTarget();
}
};
以下代码的最后两行调用message.sendToTarget
,它应该调用handleMessage
类的Handler
,但它不会!现在我不知道为什么处理程序的回调发生在一个活动而不是一个服务!我有一些解决方案如何解决这个问题(在我的代码中始终只使用AsyncTask类的API15 +),但是由于我对此没有任何了解,所以对此原因的任何解释都会非常感激!
由于
答案 0 :(得分:-2)
official document is very detail,try to read it.
请查看此链接,它可能会对您有所帮助
http://foo.jasonhudgins.com/2010/05/limitations-of-asynctask.html
行〜 注意:
当你调用cancel(boolean)方法时,onCancel函数执行。你打电话给这个吗? 功能