Android 4+上没有取消AsyncTask(适用于2.3)

时间:2013-06-26 04:14:16

标签: android android-asynctask

我遇到与此相同的情况: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 +中运行有任何线索吗?

1 个答案:

答案 0 :(得分: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();
}