简体   繁体   中英

Android AsyncTask: stop execution of the task that calls web-service

I looked for the answers here on SO, but could not find what I need. Here is the scenario that I am working on: I have an AsyncTask that makes a web service call:

class getDataDetailTask extends AsyncTask<String, Void, DataDetail> {
    @Override
    protected DataDetail doInBackground(String... args) {
        return AppUtils.getDataDetails();
    }

    @Override
    protected void onCancelled(OutageDetail result) {
        .... // something goes here   
    }
}

So let's say that the webservice call usually will timeout after 30 seconds if unsuccessful. Now, I don't want user to wait 30 seconds to find out the call has timed out, I want for it to take no more than 10 seconds. So I created a timer to look after AsyncTask:

class checkDataTask implements Runnable {
    getDataDetailTask dataAsyncTask;
    Context context;

    public checkDataTask(getDataDetailTask asyncTask) {
        dataAsyncTask = asyncTask;
    }

    @Override
    public void run() {
        mHandler.postDelayed(runnable, 10);
    }

    Handler mHandler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (dataAsyncTask.getStatus() == Status.RUNNING
                    || dataAsyncTask.getStatus() == Status.PENDING) {
                dataAsyncTask.cancel(true);
            }
        }
    };
}

all of this calls are being setup in the onCreate method in Activity like so:

    getDataDetailTask dataTask = new getDataDetailTask();
    dataTask.execute();
    checkDataTask check = new checkDataTask(dataTask);
    (new Thread(check)).start();

when AsyncTask issues cancel(true) method, onCancelled(Object) or [onCancelled() for earlier SDK versions is being called). My question is, what should i do in my onCancelled call to "kill" the task?

Just need to setup handler that will cancel the AsyncTask after given period of time:

Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
  @Override
  public void run() {
      if ( check.getStatus() == AsyncTask.Status.RUNNING )
          check.cancel(true);
  }
}, 10000 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM