androidandroid-lifecycleandroid-7.0-nougatonrestoreinstancestateonsaveinstancestate

Android - Save instance state in Application instance (TransactionTooLargeException )


Android 7.0 start throwing TransactionTooLargeException while restoring instance state if the parcel size is over the limit.

But my application have to save the loaded content which has no size limit. So it's very easy to cause this error.

Is it safe to save instance state in Application instance?

Will it be deleted while the Activity is in background?

Is there a way to save large data without throwing this exception?


Solution

  • To answers these questions one by one :

    Not if want to retrieve that data after your app's process has been killed by the OS and later restored. For that, you need to persist data to disk somehow. There are always two parts to properly handle saving state : handling configuration changes (like rotations) which do not involve process death and actual process death and restoration. Putting state in the Application instance (or any singleton) solves the first problem but not the second.

    Depends what you mean by "in the background". That can sometimes mean "the Activity exists but is in the stopped state". In that case, your data is fine. But your entire app process can be killed while the app is backgrounded and later restored when you return. In that case, your data will be gone if it is not properly saved to disk somewhere.

    Yes, write it to a database and restore the data from there instead. Alternatively, you can use this library that automatically handles persisting / restoring your Bundles to / from disk for you : https://github.com/livefront/bridge .