0

Based on Android developer's document web-page AsyncTask, Thread, it is possible to send cancel() request to AsyncTask's thread. Albeit I have sent the cancellation request and it was successful, the thread stills running. Any idea to stop the execution?

    button.setOnClickListener {
      Log.i(TAG, asyncTaskObj.status)                       // RUNNING
      if (asyncTaskObj.status == AsyncTask.Status.RUNNING) {
         asyncTaskObj.cancel(true)
         Log.i(TAG, asyncTaskObj.isCancelled)               // True
      }
      Log.i(TAG, asyncTaskObj.status)                       // RUNNING
    }

Plus, is there any simple alternative to AsyncTask, which let's restart execution of the thread? (Obviously restarting AsyncTask is not possible Q&A-2)

One more thing, I have read following questions Q&A-1, Q&A-2. However, the answers do not work for me. For instance, there is no isRunning variable.

P.S. My code is in Kotlin. Please share your idea in either Java or Kotlin.

Esmaeil MIRZAEE
  • 1,110
  • 11
  • 14
  • 1
    "Any idea to stop the execution?" -- you are stopping the execution. However, you are assuming that `cancel()` happens synchronously and `getStatus()` will return a different value immediately. `getStatus()` definitely is not yet updated by the time `cancel()` returns, based on [the source code](https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/os/AsyncTask.java). – CommonsWare Feb 22 '18 at 21:22

1 Answers1

2

It is impossible to immediately cancel a thread from the outside like that safely. You don't know what operations it might be running, what locks the thread might hold, etc. Because of that, cancel doesn't actually stop the thread immediately. It sets a flag, and it's the job of the AsyncTask to check the flag and end itself by returning from doInBackground. Do not assume any canceled thread or task will stop running instantly. If your code requires that, you need to fix your code.

As for restarting- from scratch? Create a new instance of the AsyncTask with the same parameters. From where you left off? You can do it in a couple of ways, but it takes a lot of work. And AsyncTask is not suitable for that because its thread is a shared resource among all tasks, you'll need to use an actual Thread for that.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127