Android的 - 取消的AsyncTask强行Android、AsyncTask

2023-09-11 11:23:55 作者:独揽帅氕

我在活动中的一个实现AsyncTask的:

I have implemented AsyncTask in my one of activity:

 performBackgroundTask asyncTask = new performBackgroundTask();
 asyncTask.execute();

现在,我需要实现取消按钮的功能,所以我必须停止正在运行的任务的执行。我不知道如何停止正在运行的任务(后台任务)。

Now, i need to implement the "Cancel" button functionality, so i have to stop the execution of the running task. I don't know how do i stop the running task(background task).

所以,请给我建议,我怎么取消AsyncTask的有力?

So Please suggest me, how do i cancel the AsyncTask forcefully ?

我发现了大约相同的取消()方法,但我发现,调用 取消(布尔mayInterruptIfRunning) 不一定停止后台进程的执行。所有这似乎发生的是,AsyncTask的将执行onCancelled(),并且将不运行onPostExecute()完成时

I found about the Cancel() method of the same, but i found that calling cancel(boolean mayInterruptIfRunning) doesn't necessarily stop the execution of the background process. All that seems to happen is that the AsyncTask will execute onCancelled(), and won't run onPostExecute() when it completes.

推荐答案

只是检查 isCancelled()曾经在一段时间:

Just check isCancelled() once in a while:

 protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }