onPause / onRestore with savedInstanceState

匆匆过客 提交于 2019-12-03 04:10:56

For some reason this is not documented in very very bold neon flashing letters, and took me a while to discover, but you don't need to worry about whether your activity exists or not if you simply create it with the android:launchMode=["multiple" | "singleTop" | "singleTask" | "singleInstance"] property set to "singleInstance".

Then there is only ever one instance of it, and your memory fields are preserved as long as the activity hasn't been garbage collected.

The other thing you can do is to create an Application (extended from Application) and store all your persistent objects up in that... it is created first and destroyed last as far as your entire app's life cycle is concerned (including all your activity-less services).

Just create an Application class and specify it in your manifest like this:

<application android:icon="@drawable/icon" android:label="@string/app_name"
    android:name=".MyApplication">

Then if you still REALLY want to save your values for situations where the app is going to be closed, just use SharedPreferences.

What is this onRestore method you speak of? It is not part of the Activity lifecycle... I will suppose you mean onRestart. Anyway, the reason you don't get a bundle for onRestart is because you don't need one. Your activity hasn't been officially "killed" so you don't need to restore from a saved state. Your activity was paused, but not removed from memory, so the system is just telling you that it was made visible again. You probably don't need to do anything for this sort of transition event.

Other than that, the way to do it is to save anything you consider a "state" value in the onSaveInstanceState(), then restore them in onCreate. After that you can restore any view-specific properties either on the onCreate itself, or later in the Activity lifecycle (e.g. onResume).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!