Android 為了適應不同螢幕方向的佈局資源(如 layout-land、layout-port),預設會在裝置旋轉時銷毀並重建當前 Activity。這意味著所有成員變數、View 狀態、執行緒狀態都會丟失,除非開發者主動保存與恢復。
旋轉前(銷毀階段) 旋轉後(重建階段)
┌─────────────────────┐ ┌─────────────────────┐
│ onPause() │ ──▶ │ onCreate(Bundle) │
│ onSaveInstanceState()│ │ onStart() │
│ onStop() │ │ onRestoreInstanceState()│
│ onDestroy() │ │ onResume() │
└─────────────────────┘ └─────────────────────┘
public class MainActivity extends AppCompatActivity {
private static final String KEY_TIMESTAMP = "saved_timestamp";
private static final String KEY_USER_INPUT = "user_input_text";
private static final String KEY_COUNTER = "click_counter";
private EditText inputEditText;
private TextView counterTextView;
private long lastSaveTime;
private int clickCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputEditText = findViewById(R.id.input_edit_text);
counterTextView = findViewById(R.id.counter_text_view);
// 1. 從 Bundle 恢復資料(兩種方式皆可)
if (savedInstanceState != null) {
restoreFromBundle(savedInstanceState);
}
findViewById(R.id.increment_btn).setOnClickListener(v -> {
clickCount++;
updateCounterDisplay();
});
}
// 方式一:在 onCreate 中恢復(推薦,較早執行)
private void restoreFromBundle(Bundle bundle) {
lastSaveTime = bundle.getLong(KEY_TIMESTAMP, 0);
String savedText = bundle.getString(KEY_USER_INPUT, "");
clickCount = bundle.getInt(KEY_COUNTER, 0);
inputEditText.setText(savedText);
updateCounterDisplay();
Log.d("RotationDemo", "Restored: time=" + lastSaveTime + ", count=" + clickCount);
}
// 方式二:在 onRestoreInstanceState 中恢復(onStart 之後)
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// 此處同樣可恢復資料,但比 onCreate 晚執行
}
// 儲存資料:在 onStop 之前、onPause 之後調用
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
lastSaveTime = System.currentTimeMillis();
outState.putLong(KEY_TIMESTAMP, lastSaveTime);
outState.putString(KEY_USER_INPUT, inputEditText.getText().toString());
outState.putInt(KEY_COUNTER, clickCount);
Log.d("RotationDemo", "Saved: time=" + lastSaveTime + ", count=" + clickCount);
}
private void updateCounterDisplay() {
counterTextView.setText("點擊次數: " + clickCount);
}
}
擁有 android:id 的 View 會自動保存與恢復部分狀態:
EditText:輸入文字、游標位置、選取範圍ScrollView、RecyclerView:捲動位置CheckBox、RadioButton、Switch:勾選狀態WebView:需手動呼叫 saveState()/restoreState()注意:自動保存要求 View 必須設定 android:id,且 ID 在旋轉前後保持一致。
Bundle 有大小限制(約 50KB-100KB),且僅支援基本型別與 Parcelable/Serializable。大量資料建議採用以下策略:
public class RotationViewModel extends ViewModel {
private final SavedStateHandle handle;
private MutableLiveData> userList;
public RotationViewModel(SavedStateHandle handle) {
this.handle = handle;
}
public LiveData> getUserList() {
if (userList == null) {
// 從 SavedStateHandle 恢復或重新載入
userList = handle.getLiveData("user_list", new MutableLiveData<>());
if (userList.getValue() == null) {
loadUserListFromRepository();
}
}
return userList;
}
private void loadUserListFromRepository() {
// 從資料庫/網路載入,完成後 postValue 更新
}
}
@Override
public Object onRetainNonConfigurationInstance() {
// 僅保留非配置相關的大型物件,如執行緒、資料庫連線
return heavyDataObject;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Object retained = getLastNonConfigurationInstance();
if (retained != null) {
heavyDataObject = (HeavyDataObject) retained;
}
}
SavedStateHandle 自動處理旋轉保存,程式碼最簡潔android:screenOrientation="portrait"NullPointerException 在恢復時:檢查 savedInstanceState != null 後再讀取super.onSaveInstanceState() 在自定儲存邏輯之後呼叫android:id、佈局檔案旋轉前後 ID 是否一致