How can Saved Instance State read/write to disk in Android?

99 Views Asked by At

According to Android developer documentation as of March 1, 2023, Saved Instance State is slow to read/write.
This is because it requires a serialization/deserialization process and requires disk access.

My understanding is that Saved Instance State uses a Bundle object to store data, and the data will be restore using a Bundle object at onCreate and onRestoreInstanceState.

My question is, since the Bundle object will be stored in memory, how can it access the disk to read/write the stored data?

Due to these questions, I'm also confusing how SavedInstanceState can safely recover from process destruction, since at the time the process is destroyed by the System, the memory will also be destroyed.

Thanks.

I've attached a relevant developer documentation link and a diagram below.

Android Developers - Save UI States

enter image description here

2

There are 2 best solutions below

2
Gabe Sechan On

Because the data needs to be stored to disk at some point. The OS may actually terminate your process and restart it later, passing in a Bundle that matches the one your returned from saveInstanceState. To make this happen, it needs to serialize it to disk, so it's saved between process instances. Whether or not the OS actually will write it to disk is an implementation detail of the OS- it may not in all cases. But it can.

Of course since it's Bundle backed I wouldn't worry about the speed of reading the Bundle. I'd worry more about the size limitation (which is 1-2MB) or a Bundle, and which you'll crash if you exceed.

2
CommonsWare On

My question is, since the Bundle object will be stored in memory, how can it access the disk to read/write the stored data?

IMHO, this is a documentation bug. For the purposes of that table, I would have gone with "quick, but requires inter-process communication (IPC)". A classic Bundle is not persistable and is not persisted.

Android 5.x introduced a version of onSaveInstanceState() and onRestoreInstanceState() that take both a Bundle and a PersistableBundle. The latter is indeed persisted. However, the first row of your table indicates to me that they are not considering that scenario.

Ideally, this table would have five columns, two of which are "Saved Instance State", covering the Bundle and the PersistableBundle scenarios.