【发布时间】:2013-06-26 12:49:25
【问题描述】:
我的情况和这里一样:Android AsyncTask won't stop when cancelled, why?
我设置了一个计时器在几秒钟后终止 AsyncTask。 它在android 2.3.5上完美运行(任务在我设置的超时后被取消),但由于某种原因它在android 4+上不起作用)
这是相关代码(都在AsyncTask类里面)
private class TaskKiller extends TimerTask {
private AsyncTask<?, ?, ?> mTask;
public TaskKiller(AsyncTask<?, ?, ?> task) {
mTask = task;
}
public void run() {
mTask.cancel(true);
}
}
@Override
protected String doInBackground(Void... nothing) {
// Setting the Task timeout.
Timer timer = new Timer();
timer.schedule(new TaskKiller(this), 3000);
response = HttpRequest(url); // this method makes an HttpPost request.
// This, I think, is where android 4+ is unable to cancel the task (while making the http request). It is perfectly cancelled in 2.3.5, though.
}
@Override
protected void onCancelled() {
Log.e("TASK CANCELED","...");
}
它在 android 2.3 中就像一个魅力。
您对如何使其在 android 4+ 中工作有任何线索吗?
【问题讨论】:
-
尝试在取消异步任务后放置中断。
-
stackoverflow.com/questions/16538714/…。检查这可能会有所帮助