Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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... values) {
        super.onProgressUpdate(values);
        gender.setText(values[0]);
}

My problem is how to check if the activity which the gender TextView rendered from, is still available?

If not, I will get an error and my application will shut down.

like image 693
Asaf Nevo Avatar asked Jun 25 '12 12:06

Asaf Nevo


People also ask

How do I know if AsyncTask is running?

Use getStatus() to get the status of your AsyncTask . If status is AsyncTask. Status. RUNNING then your task is running.

What happens to AsyncTask if activity is destroyed?

If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.

Why AsyncTask is deprecated in android?

This class was deprecated in API level 30.AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

How to cancel AsyncTask in android?

AsynTaskExample mAsyncTask = new AsyncTaskExample(); mAsyncTask. cancel(true);


2 Answers

You can cancel your asynctask in the activity's onDestroy

@Override
protected void onDestroy() {
    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]);
    }
}
like image 61
ColdFire Avatar answered Oct 30 '22 17:10

ColdFire


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:

volatile boolean running;

public void onActivityCreated (Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


public void onDestroy() {
    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.

like image 20
IanB Avatar answered Oct 30 '22 17:10

IanB