Thursday 16 July 2020

What happens to running AsyncTask when Activity Changes ?

Hi Guys,
Today I am going to discuss the topic of what will happen to the on-going/ running async task when the activity changes.

AsyncTask is used to perform intensive tasks off the UI thread. It is defined by a computation that runs on a background thread and publishes the result in Main Thread or UI Thread.

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 navigates to another activity, current activity will be destroyed or go in background activity stack and new activity would be in the 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.

To resolve this problem, one option is to use IntentService along with a BroadcastReceiver to deliver result.

Another option is to run AsyncTask into worker fragment, as fragment is the cleanest way to handle configuration changes because fragment has the ability to retain their instances simply by calling setRetainInstance(true) in one of its lifecycle methods.


Thank you for Reading,
Swetabh


No comments:

Post a Comment

What is Image Stabilization? OIS and EIS explained.

Hi Guys, Today I'm going to talk about image stabilization, what are OIS and EIS? How these works and What are the advantages of having ...