两种销毁
第一种是正常的销毁,好比用户按下Back按钮或者是activity本身调用了finish()方法;函数
另外一种是因为activity处于stopped状态,而且它长期未被使用,或者前台的activity须要更多的资源,这些状况下系统就会关闭后台的进程,以恢复一些内存。编码
须要注意的是这其中有一种状况就是屏幕旋转的问题,当用户旋转手机屏幕,每一次都会致使activity的销毁和从新创建。spa
在第二种状况下,尽管实际的activity实例已经被销毁,可是系统仍然记得它的存在,当用户返回到它的时候,系统会建立出一个新的实例来代替它,这里须要利用旧实例被销毁时候存下来的数据。这些数据被称为“instance state”,是一个存在Bundle对象中的键值对集合。rest
缺省状态下,系统会把每个View对象保存起来(好比EditText对象中的文本,ListView中的滚动条位置等),即若是activity实例被销毁和重建,那么不须要你编码,layout状态会恢复到前次状态。对象
可是若是你的activity须要恢复更多的信息,好比成员变量信息,则须要本身动手写了。blog
onSaveInstanceState()
若是要存储额外的数据,必须覆写回调函数onSaveInstanceState().进程
系统会在用户离开activity的时候调用这个函数,而且传递给它一个Bundle object,若是系统稍后须要重建这个activity实例,它会传递同一个Bundle object到onRestoreInstanceState() 和 onCreate() 方法中去。内存
当系统中止activity时,它会调用onSaveInstanceState()(过程1),若是activity被销毁了,可是须要建立一样的实例,系统会把过程1中的状态数据传给onCreate()和onRestoreInstanceState()(图中标出的2和3)。资源
存储Activity状
当系统中止activity时,系统会调用onSaveInstanceState(),状态信息会以键值对的形式存储下来。
默认的实现中存储了activity的view系列的状态,好比文本和滚动条位置等。
要存储额外的信息,必须本身实现onSaveInstanceState(),而且给Bundle object加上键值对。
- static final String STATE_SCORE = "playerScore";
- static final String STATE_LEVEL = "playerLevel";
- ...
- @Override
- public void onSaveInstanceState(Bundle savedInstanceState) {
- // Save the user's current game state
- savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
- savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
- // Always call the superclass so it can save the view hierarchy state
- super.onSaveInstanceState(savedInstanceState);
- }
要记得调用基类的实现,以实现默认的实现。
恢复Activity状态
当activity重建时,须要根据Bundle中的状态信息数据恢复activity。onCreate() 和onRestoreInstanceState()回调函数都会接收到这个Bundle。
由于每次建立新的activity实例的或重建一个实例的时候都会调用onCreate()方法,因此必须先检查是否Bundle是null,若是是null,则代表是要建立一个全新的对象,而不是重建一个上次被销毁的对象。
好比onCreate()方法能够这么写:
- @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是否为null。
- 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);
- }
此处也要注意,不要忘记调用基类实现。