Async Task and Life cycle events

Async task is a way by which android enables off-loading long running tasks like accessing the network or writing to a db. The main purpose being to keep the main thread, which runs the UI,  as free as possible so that UI does not lag and feel janky.

How Async task works and the various methods of the Async task is covered by the android dev site in a great depth and I would like to cover how life cycle methods affect async tasks.

Consider the following scenario :

User wants to download a file from a server  and activity offers a minimalistic UI with just a button to start the download and a textview to update the current download status.

The activity spins off an async task to handle the download operation and the onPostExecute will update a textview with the result. After the download has started if the user rotates the screen (or any other significant event like changing the font size) , android will recreate the activity and the older activity runs through all its life cycle events and is destroyed. Now when the async task returns no longer has the right reference to either the activity which started it or a reference to the TextView where the result has to be populated.

This can lead to unexpected behavior like losing the progress of async task or even worse the recreated activity can start another async task with the same download.

The old way of addressing this problem :

Before API 13, overriding the onRetainNonConfiguration and getLastNonConfigurationInstance() did the trick. We save the reference to the async task in onRetainNonConfiguration() and return it in getLastNonConfiguration(). But these methods are now deprecated.

Recommended way of addressing the issue : 

We can manage the object inside the fragment by using the fragments method setRetainInstance(true).

The setRetainInstance method holds on to the reference of the fragment even if the activity is destroyed  and is managed  and guaranteed to work by the framework. This way we can create a view less fragment which spins off the Async task on behalf of the activity and has call backs to the activity. This way we do not hold on to any reference to the view that is being destroyed.

Pasting code in word-press is a pain, for now please check the github link for the code samples, while I look for alternate solutions.

https://github.com/srikanth569/AsyncTaskLifeCycle

SK

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s