UI updates across config changes: The weird point

2019-08-24 10:03发布

问题:

I am an experienced Android developer and it is a shame that I am still ineffectively fighting against fundamental issues like persisting UI changes across configuration changes.

I know, this is an all too well known problem and there exists a lot of literature on it. The recommended solution is to setRetainInstance(true) a UI-less fragment:

https://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

Best practice: AsyncTask during orientation change

For the sake of completeness, let me draw up the scenario. You have an AsyncTask that performs a Network request and is supposed to update the UI in onPostExecute()

I see some issues with the proposed solution:

  • The proposed solution says that onPostExecute() is guaranteed to not be called during between the calls to onDetach() and the next onAttach() but what if the AsyncTask returns early(after Activity's onPause() and before the call to onDetach()). If onPostExecute() executes during the period, since onSaveInstanceState() will have been called, any update to the Views will not persist across Activity restart.
  • Second if the AsyncTask returns such that onPostExecute() executes before the call to Activity's onCreate() then the views will not have been initialized for any view updates to be pushed yet.

Is there any effective solution against this problem that addresses memory leaks and state save across config changes?