Skip to content Skip to sidebar Skip to footer

Android Asynctasks How To Check If Activity Is Still Running

I have used AsyncTasks with my application, in order to lazy download and update the UI. For now my AsyncTasks updates the UI real simply: protected void onProgressUpdate(String...

Solution 1:

You can cancel your asynctask in the activity's onDestroy

@OverrideprotectedvoidonDestroy() {
    asynctask.cancel(true);
    super.onDestroy();
}

and when performing changes you check whether your asynctask has been cancelled(activity destroyed) or not

protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    if(!isCancelled()) {
         gender.setText(values[0]);
    }
}

Solution 2:

I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:

volatileboolean running;

publicvoidonActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


publicvoidonDestroy() {
    super.onDestroy();

    running=false;
    ...
}

Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.

Solution 3:

Try

if (!isFinishing()) {
    gender.setText(values[0]);
}

Solution 4:

Check whether activity is running or not

 if (!isFinishing()) {
  // Do whatever you want to do
}

Solution 5:

I will insist that you that if you Activity is not running why don't you cancel the AsyncTask? That would be a better and feasible solution. If you Application is running say you move from one Activity to another then it won't give error AFAIK.

But, I would insist to cancel the AsyncTask then you'r Activity is not running, you can check AsyncTask is running or not,

if(task != null && task.equals(AsyncTask.Status.RUNNING))
task.cancel(true);

Post a Comment for "Android Asynctasks How To Check If Activity Is Still Running"