[安卓教程翻译]4.4 Recreating an Activity
当用户按下“返回”键,或者activity中调用了finish()方法,activity都将被应用程序销毁。如果activity进入stopped状态并且很长时间都没有再次被使用,或者处于前台的activity需要更多资源所以系统不得不关闭后台进程来恢复内存,这些情况下,activity被系统销毁。
当activity被销毁是由于用户按下“返回”键或者activity调用finish()方法,系统对该Activity对象的概念将永远消失,因为这些行为表明该activity不再被需要。不过,如果系统销毁activity是因为系统限制(而不是正常的应用程序行为),那么尽管Activity对象被销毁,系统仍然记得它的存在,如果用户希望返回,系统将创建一个新的activity实例,并用一系列保存的数据来描述被销毁时activity的状态。这些数据叫做“instance state”,是储存在Bundle对象中的一系列键值对的集合。
注意:每当你旋转屏幕,activity将被销毁并重建。当屏幕改变方向,系统会销毁并重建处于前台的activity,这是因为屏幕的配置改变了,activity可能需要重新加载资源(比如layout)。
默认情况下,系统使用Bundle对象的状态信息来保存activity布局中每个view的信息(比如EditText对象中输入的文本值)。因此,如果activity对象被销毁又重建,你不需要写任何代码,布局的状态就可以恢复到之前的状态。然而,你可能希望保存更多activity的状态信息,比如成员变量。
注意:为了让android系统能够储存activity中没一个view的状态,每个view都必须有唯一的ID,由android:id属性来指定。
为了保存更多activity状态的数据,必须重写onSaveInstanceState()回调函数。当用户离开activity时系统会调用该方法,并传递一个Bundle对象,当activity意外被终止时,该对象将被保存。如果稍后系统需要重建activity实例,将会把相同的Bundle对象传递给onRestoreInstanceState()和onCreate()方法。

Figure 2. As the system begins to stop your activity, it calls onSaveInstanceState() (1) so you can specify additional state data you'd like to save in case the Activity instance must be recreated. If the activity is destroyed and the same instance must be recreated, the system passes the state data defined at (1) to both the onCreate() method (2) and the onRestoreInstanceState() method (3).
Save Your Activity State
当activity准备进入stopped状态,系统会调用onSaveInstanceState(),所以activity能够保存状态信息(通过键值对集合)。默认情况下,该方法会保存activity中组件层次结构的状态,例如EditText组件的文本,或者ListView的滚动条位置。
如果要为activity保存更多的状态信息,必须实现onSaceInstanceState()并向Bundle对象中增加键值对。例如:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Always call the superclass first // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) { // Restore value of members from saved state mCurrentScore = savedInstanceState.getInt(STATE_SCORE); mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL); } else { // Probably initialize members with default values for a new instance } ... }
与其在onCreate()中恢复这些状态,你也可以选择实现onRestoreInstanceState()方法,该方法在onStart()方法之后被调用。系统仅在需要恢复状态时才调用onRestoreInstanceState()方法,所以不必检查Bundle是否为空:
public void onRestoreInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState); // Restore state members from saved instance mCurrentScore = savedInstanceState.getInt(STATE_SCORE); mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL); }
注意:记得要调用onRestoreInstanceState()的父类方法,这样才能保证默认的组件层级结构状态被恢复。

浙公网安备 33010602011771号