【问题标题】:AsyncTask is not being cancelled on Android 4+ (works on 2.3)AsyncTask 在 Android 4+ 上没有被取消(适用于 2.3)
【发布时间】: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+ 中工作有任何线索吗?

【问题讨论】:

标签: android android-asynctask


【解决方案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();
}

【讨论】:

  • 好主意。我没有想到如果。不幸的是,eclipse 显示错误并要求我“添加演员表”到 mRequest(它添加了一个计时器演员表!)。所以到目前为止,它不起作用。我将测试类似的方法并返回。
  • 解决方案很简单。我不得不使用 mRequest.abort() 而不是“mRequest.cancel()”,并且它起作用了。感谢这个简单明了的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-16
  • 2014-03-23
相关资源
最近更新 更多