brian
brian

Reputation: 6912

How to cancel AsyncTask on Android

I have a AsyncTask as below:

private class SearchTask extends AsyncTask<Object, Object, Object> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        System.out.println("Start");
    }

    @Override
    protected Object doInBackground(Object... urls) {
        SearchFunction();
        return null;
    }

    @Override
    protected void onPostExecute(Object result) {
        System.out.println("End");
    }
}

And a Timer as below:

private Handler handler = new Handler();
private Runnable updateTimer = new Runnable() {
    public void run() {
        System.out.println("===status===");
        System.out.println(SearchTask.getStatus());

        SearchTask.cancel(true);
    handler.postDelayed(updateTimer, 3000);
    }
};

And call AsyncTask and timer code as below:

            handler.postDelayed(updateTimer, 3000);
            SearchTask SearchTask = new SearchTask();
            SearchTask.execute();

The SearchFunction method in doInBackground maybe spend more than 3 seconds, so add a timer.
But in updateTimer first call and cancel the AsyncTask, the doInBackground is still running until it finished, and then cancel onPostExecute.
How can I do to cancel doInBackground direct?

Upvotes: 0

Views: 212

Answers (2)

user2482895
user2482895

Reputation:

Just check isCancelled() once in a while and try it out:

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

Upvotes: 1

user2652394
user2652394

Reputation: 1686

Basically you can't do that. The best thing is when you set cancel(true) means you will ignore the code running on the onPostExecute() (maybe put an if statement there). Hope this helps.

Upvotes: 1

Related Questions