0

我的情况和这里一样:Android AsyncTask 取消时不会停止,为什么?

我设置了一个计时器以在几秒钟后终止 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+ 中工作有任何线索吗?

4

1 回答 1

1
private HttpUriRequest mRequest;


protected String doInBackground(Void... nothing) {
    ...
    mRequest = new HttpGet(url); // or HttpPost
    response = client.execute(mRequest);
    ...
}

private void myCancelationRoutine() {
      mRequest.cancel();
      mTask.cancel();
}
于 2013-06-26T04:49:25.527 回答