sequenceDiagram
LocalPersistence->>AMS: user open activity
activate AMS
AMS->>ActivityViewModelScope: start
activate AMS
activate ActivityViewModelScope
ActivityViewModelScope->>Activity: start
activate Activity
AMS->>ActivityViewModelScope: rotation/relaunch
rect rgb(199, 237, 204)
ActivityViewModelScope->>Activity: rotation/relaunch
Activity->>Activity: destory,retainNonConfigurationInstance
deactivate Activity
Activity->>Activity: launch,attach恢复lastNonConfigurationInstances
activate Activity
deactivate Activity
end
rect rgb(253, 245, 230)
AMS->>ActivityViewModelScope: killApplicatonOrActivity by system
ActivityViewModelScope->>AMS: onStop,saveInstanceState
deactivate ActivityViewModelScope
activate AMS
deactivate AMS
AMS->>ActivityViewModelScope: restart
activate ActivityViewModelScope
AMS->>ActivityViewModelScope: onstart,restoreInstanceState
deactivate ActivityViewModelScope
end
deactivate AMS
rect rgb(151,255,255)
AMS->>LocalPersistence: save data to local persistence
LocalPersistence->>AMS: user leave activity
deactivate AMS
LocalPersistence->>AMS: next time user open activity
activate AMS
AMS->>LocalPersistence: user restore data from local persistence
deactivate AMS
end
https://developer.android.com/topic/libraries/architecture/saving-states#options
ViewModel | Saved instance state | Persistent storage | |
---|---|---|---|
Storage location | in memory | serialized to disk | on disk or network |
Survives configuration change | Yes | Yes | Yes |
Survives system-initiated process death | No | Yes | Yes |
Survives user complete activity dismissal/onFinish() | No | No | Yes |
Data limitations | complex objects are fine, but space is limited by available memory | only for primitive types and simple, small objects such as String | only limited by disk space or cost / time of retrieval from the network resource |
Read/write time | quick (memory access only) | slow (requires serialization/deserialization and disk access) | slow (requires disk access or network transaction) |