Finish the last Asynctask before starting another

Asked

Viewed 258 times

2

I’m wearing a AsyncTask (Android app) to receive a string json from the server (Comes from a controller on my ASP MVC site). Basically everything that comes from the server goes through this class

public class Communications extends AsyncTask<String, Void, String> {
     //vários caminhos aqui dentro
}

and in the onPostExecute I send information where it is needed and start several activities (depending on what was requested from the server). The problem is when the answer takes time and I start one more AsyncTask on top. How can I know if there is a task going on, and if it is running, how to cancel it?

2 answers

5

By default tasks, created using the Asynctask class, are executed sequentially in a single background thread.

To know the status of a task use the method getStatus(). He returns a enum of the kind Asynctask.Status, whose values are:

  • FINISHED - Indicates that the task was executed and the method onPostExecute() was called and finished.
  • PENDING - Indicates that the task has not yet started.
  • RUNNING - Indicates that the task is running.

To cancel a task use the method Cancel().

Calling this method will result in calling onCancelled() upon return doInBackground(), ensuring that onPostExecute() never be called.
In the method doInBackground() must be periodically checked the value returned by isCancelled() and, if true, finish the task as soon as possible.

1


I was able to solve the problem with the help of the @ramaral user response Below is the code snippet that starts all AsyncTask, and if you’re running the previous one it cancels it and starts the latest one.

public class WebserviceJson {

  public static AsyncTask communicationTask;

  public static void callWebServiceJson(final Activity caller, String url, final String params) {
    final String[] parms = new String[3];
    parms[0] = url;
    parms[1] = params;

    ConnectivityManager cm = (ConnectivityManager) caller.getSystemService(Context.CONNECTIVITY_SERVICE);

        if(communicationTask == null){
            communicationTask = new Communications(caller).execute(parms);
        }
        else if(communicationTask.getStatus() != AsyncTask.Status.RUNNING)

            communicationTask = new Communications(caller).execute(parms);
        else {

            communicationTask.cancel(true);
            communicationTask = new Communications(caller).execute(parms);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.