简体   繁体   English

我应该在onCreate还是onRestoreInstanceState中恢复savedinstancestate?

[英]Should I restore savedinstancestate in onCreate or in onRestoreInstanceState?

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. 我重写了onSaveInstanceState,以便添加需要保留和恢复的数据。

When the activity gets destroyed and recreated, onCreate is passed the savedInstanceState bundle; 当活动被销毁并重新创建时,onCreate将传递savedInstanceState包; but also onRestoreInstanceState() is called and passed the same bundle. 而且调用onRestoreInstanceState()并传递相同的bundle。

So where should I put the code that extracts the data from the bundle and restores the state? 那么我应该在哪里放置从包中提取数据的代码并恢复状态? In onCreate or in onRestoreInstanceState? 在onCreate或onRestoreInstanceState中? Is the latter guaranteed to be always called? 保证后者始终被称为?

Is it possible that onRestoreInstanceState is called without calling onCreate? 是否有可能在不调用onCreate的情况下调用onRestoreInstanceState? (eg if the activity gets stopped and restarted but not destroyed and recreated)? (例如,如果活动停止并重新启动但未被销毁和重新创建)?

"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" “而不是在onCreate()期间恢复状态,你可以选择实现onRestoreInstanceState(),系统在onStart()方法之后调用。只有当存在要恢复的保存状态时,系统才会调用onRestoreInstanceState(),所以你不要需要检查Bundle是否为NULL“

following link explain pretty clearly about restart activity. 以下链接清楚地解释了重启活动。

Android Guide Android指南

Android在onStart()和onResume()生命周期方法之间调用onRestoreInstanceState()方法。因此,为了恢复活动状态,只需实现onRestoreInstanceState()方法恢复活动状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM