I couldn't find any solution to this problem that satisfies all my requirements.
In my application I use AsyncTasks
to perform some operations like saving data to a memory or reading data from a database. I create a progress dialog in onPreExecute
, update a progress value in onProgressUpdate
and dismiss the dialog in onPostExecute
.
Recently I switched to the Fragment API (I use the Support Library to target older versions of Android), meaning that my activities subclass FragmentActivity
and dialogs subclass DialogFragment
.
Switching to the Fragment API caused a well-known problem - sometimes I get the following exception:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
This happens, for instance, when a user starts a background operation (a progress dialog appears), uses the home button to minimize the application and the operation finishes when the activity is in background. The application then tries to dismiss the dialog and this fails since the state of the activity was saved.
I understand the issue. It can be fixed by ensuring that changes to the UI are postponed until the activity is resumed as described in this post: How to handle Handler messages when activity/fragment is paused.
However, this solution leads to another problem. What if the operation finishes when the activity is in background and later the activity is killed by Android? When a user navigates back to the application, it restores its state that was saved in onSaveInstanceState
. Therefore, the progress dialog is still visible with the same progress value as when the activity was put into background. A message that should dismiss it, was never processed and it was lost when the activity was killed.
What is the correct solution that handles all the described issues properly? How to allow for changing the UI when the activity is in background or, at least, allow for postponing UI changes and ensuring they won't be lost in case the activity is killed by Android? The solution must allow for tracking progress of a background task.