我有同樣的情況如下:Android AsyncTask won't stop when cancelled, why?的AsyncTask未在Android取消4+(適用於2.3)
我設置一個計時器,幾秒鐘後殺的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+的工作?
嘗試取消後取消asynctask中斷。 – Riser
http://stackoverflow.com/questions/16538714/stop-asynctask-doinbackground-method/16538887。檢查這可能有幫助 – Raghunandan