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