Terminate the last AsyncTask before starting another

2

I'm using AsyncTask (Android App) to get a string json from the server (Comes from a controller from 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 onPostExecute I send the information where it is needed and start several activities (depending on what was requested from the server). The problem is when the response is delayed and I start another%% of% over. How do I know if there is a task to be done, and if it is running, how can I cancel it?

    
asked by anonymous 24.05.2017 / 20:19

2 answers

1

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

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);
    
20.07.2017 / 12:22
5

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

To learn the status of a task, use the getStatus () method. . It returns a enum of type AsyncTask.Status , whose values are:

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

To cancel a task, use the cancel () .

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

    
25.05.2017 / 00:04