简体   繁体   中英

state of AsyncTask when the activity gets destroyed

In my main activity I have an AsyncTask running which in postExecute() updates a ListView. Now before postExecute() gets called if my activity gets destroyed due to any reason what would be the state of the AyncTask . onPostExecute() UI updations will throw exception.

One way I thought is to cancel the ayncTask in onDestory() . But if the asynctask is in postExecute when on destroy gets called how to handle it.

But if the asynctask is in postExecute when on destroy gets called how to handle it.

This case simply cannot happen, because both methods are called on the UI Thread, meaning one is finished before the other is called.

When your UI is no longer available (in onDestroy ), cancel your AsyncTask .

In onPostExecute you can check the cancel status of the AsyncTask . You can also check isFinishing on the Activity .

Some how u can handle ur code exception like this,U can handle exception in the AsyncTask

public abstract class ExceptionAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

    private Exception exception=null;
    private Params[] params;

    @Override
    final protected Result doInBackground(Params... params) {
        try {
            this.params = params; 
            return doInBackground();
        }
        catch (Exception e) {
            exception = e;
            return null;
        }
    }

    abstract protected Result doInBackground() throws Exception;

    @Override
    final protected void onPostExecute(Result result) {
        super.onPostExecute(result);
        onPostExecute(exception, result);
    }

    abstract protected void onPostExecute(Exception exception, Result result);

    public Params[] getParams() {
        return params;
    }

}

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