Should I restore savedinstancestate in onCreate or in onRestoreInstanceState?

天大地大妈咪最大 提交于 2020-01-23 04:26:28

问题


I have an activity that starts some other activities for results, so when the result comes back, the activity may or may not have been destroyed and recreated.

I have overridden onSaveInstanceState so as to add the data that needs to be preserved and restored.

When the activity gets destroyed and recreated, onCreate is passed the savedInstanceState bundle; but also onRestoreInstanceState() is called and passed the same bundle.

So where should I put the code that extracts the data from the bundle and restores the state? In onCreate or in onRestoreInstanceState? Is the latter guaranteed to be always called?

Is it possible that onRestoreInstanceState is called without calling onCreate? (e.g. if the activity gets stopped and restarted but not destroyed and recreated)?


回答1:


"Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is NULL"

following link explain pretty clearly about restart activity.

Android Guide




回答2:


The onRestoreInstanceState( ) method is invoked by Android between the onStart( ) and the onResume( ) lifecycle methods.So, in order to restore the state of your activity, simply implement the onRestoreInstanceState( ) method restore activity state.



来源:https://stackoverflow.com/questions/23472415/should-i-restore-savedinstancestate-in-oncreate-or-in-onrestoreinstancestate

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