如果你是一个有经验的 Android 程序员,那么你肯定手写过许多 onSaveInstanceState
以及 onRestoreInstanceState
方法用来保持 Activity 的状态,因为 Activity 在变为不可见以后,系统随时可能把它回收用来释放内存。重写 Activity 中的 onSaveInstanceState
方法 是 Google 推荐的用来保持 Activity 状态的做法。
Google 推荐的最佳实践
onSaveInstanceState
方法会提供给我们一个 Bundle
对象用来保存我们想保存的值,但是 Bundle
存储是基于 key - value 这样一个形式,所以我们需要定义一些额外的 String
类型的 key 常量,最后我们的项目中会充斥着这样代码:
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); } |