android – What happens to running AsyncTasks when the Activity changes?-ThrowExceptions

Exception or error:

While Network Operation is running in Asynctask, If user press the Back button and switch to another activity what will happen to Asynctask which is running in background?

  1. AsyncTask Process automatically Kill by OS?

  2. Async Task complete it’s entire operation?

How to solve:

AsyncTask is an abstract Android class which helps the Android applications to handle the Main UI thread in efficient way. AsyncTask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread.

1. AsyncTask processes are not automatically killed by the OS. AsyncTask processes run in the background and is responsible for finishing it’s own job in any case. You can cancel your AsycnTask by calling cancel(true) method. This will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object) method is called instead of onPostExecute() after doInBackground() returns.

2. After completion of it’s operation, the background thread it’s working on is stopped. AsyncTask has an onPostExecute() which is called once your work is finished. This method is called after doInBackground() method completes processing. Result from doInBackground() is passed to this method.

###

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.

Similarly if user navigate to another activity,current activity will be destroyed or go in background activity stack and new activity would be in foreground.

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. Indeed it updates the former instance of the activity that is not displayed anymore. This can lead to an Exception of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity.

###

AsyncTask will still run and try to post result on Zombie Activity. Best is to user AsyncTaskLoader.

Leave a Reply

Your email address will not be published. Required fields are marked *