`
weiweirenhong
  • 浏览: 32581 次
  • 性别: Icon_minigender_1
  • 来自: 西安
最近访客 更多访客>>
社区版块
存档分类
最新评论

Application Fundamentals--Saving activity state(保存activity实例的状态信息)

阅读更多
Saving activity state--保存activity实例的状态信息

When the system, rather than the user, shuts down an activity to conserve memory, the user may expect to return to the activity and find it in its previous state.【翻译:系统需要更多内存资源的时候会销毁activity实例,用户希望系统能够在实例重新回到前台的时候能恢复之前的状态信息。】

To capture that state before the activity is killed, you can implement an onSaveInstanceState() method for the activity. Android calls this method before making the activity vulnerable to being destroyed — that is, before onPause() is called. It passes the method a Bundle object where you can record the dynamic state of the activity as name-value pairs. When the activity is again started, the Bundle is passed both to onCreate() and to a method that's called after onStart(), onRestoreInstanceState(), so that either or both of them can recreate the captured state.

翻译:在activity被销毁之前要想俘获实例的状态信息,开发者需要在activity中实现onSaveInstanceState()方法,Android系统会在被销毁之前调用该方法,准确说是在 onPause()方法被调用之前,系统会调用onSaveInstanceState()方法。这个方法的参数是一个Bundle对象,这个参数中以name-value的形式持有这个activity实例的属性状态信息。当这个activity类的另外一个实例被创建的时候,这个Bundle对象会作为参数传递给onCreate() 、onStart() 和onRestoreInstanceState(), 方法。所以在这三个方法中,都可以恢复activity实例之前的状态信息。

Unlike onPause() and the other methods discussed earlier, onSaveInstanceState() and onRestoreInstanceState() are not lifecycle methods. They are not always called. For example, Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key). In that case, the user won't expect to return to the activity, so there's no reason to save its state.

翻译:onSaveInstanceState() 和 onRestoreInstanceState()方法与我们之前讨论过的其他生命周期回调方法不同,这两个方法不是生命周期方法,这两个方法不总是被系统调用,例如:Android系统会在activity实例被销毁前调用onSaveInstanceState()方法,系统不会在按下BACK键的时候(实例弹出当前task堆栈,这时候实例也被销毁)多余地去调用onSaveInstanceState()方法。因为这时候用户其实并不期望再次返回到该实例的界面,所以不需要保存该实例的状态信息。

Because onSaveInstanceState() is not always called, you should use it only to record the transient state of the activity, not to store persistent data. Use onPause() for that purpose instead.

正是因为onSaveInstanceState() 不是经常被系统调用,所以,开发者实现该方法通常是为了保留activity实例的临时状态信息,如果是需要保存activity实例的持久化信息,应该是在onPause()方法中实现。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics