when is onRestoreInstanceState called?

后端 未结 6 821
有刺的猬
有刺的猬 2020-12-01 08:49

Sorry for my incomprehension, but I am new in the android development.

I have an application with activity A and activity B in it, and I go from activity A to activi

相关标签:
6条回答
  • 2020-12-01 09:27

    I used in this case a flag and SharedPreferences. This should work, and when you change the screen orientation.

    0 讨论(0)
  • 2020-12-01 09:30

    Saving and restoring state is meant to save the current temporary data that is obsolete when user exits the application. When you minimize or leave the Activity by opening next one it might be killed by the system due to lack of resources and restarted with savedInstanceState when you get back to it. So use onSaveInstanceState() only for saving minimize-restore session data.

    So if you start a new Activity in front and get back to the previous one (what you are trying to do), the Activity A might not be killed (just stopped) and restarted without going being destroyed. You can force killing it and restoring by checking Don't keep activities in developer options menu.

    If you call finish() or remove the Activity from recent task list the savedInstanceState will not be passed to onCreate() since the task was cleared.

    If the value must be persistent consider using SharedPreferences.

    0 讨论(0)
  • 2020-12-01 09:40

    To answer your question, have a look at the android doc: https://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)

    It says that onRestoreInstanceState is called after onStart() method in the activity lifecycle.

    0 讨论(0)
  • 2020-12-01 09:44

    reference

    onSaveInstanceState

    ... onPause()-> onSaveInstanceState() -> onStop() -> onDestory()
    

    onRestoreInstanceState

    onCreate()-> onStart()-> onRestoreInstanceState()-> onPostCreate(Bundle) ...
    

    Or You can use LiveData. Save the states in it and observe.If the device rotates it'll update the views accordingly.

    0 讨论(0)
  • 2020-12-01 09:47

    After onStart() which is after onCreate()

    0 讨论(0)
  • 2020-12-01 09:49

    This happens because you are navigating the hard way. If you used the phone's default back button navigation, your onCreate would get the bundle passed in.

    To circumvent this issue, I suggest you save your state to shared preferences as well as a back up. When the bundle is null, restore it from the shared preferences.

    0 讨论(0)
提交回复
热议问题