編輯:關於 Android 程式設計
屏幕一旋轉,用戶剛剛填了一半的表單就沒了——這是每個 Android 新手都遇到過的問題。本文從源碼出發,把「什麼時候保存、保存什麼、保存到哪裡」這幾個問題逐一回答清楚。
用戶數據是在 Activity 與用戶交互的過程中產生的,所以要保存數據,第一個該翻開的就是 Activity 的源碼註釋。
* <ul>
* <li> {@link #onCreate} is where you initialize your activity. Most
* importantly, here you will usually call {@link #setContentView(int)}
* with a layout resource defining your UI, and using {@link #findViewById}
* to retrieve the widgets in that UI that you need to interact with
* programmatically.
* <li> {@link #onPause} is where you deal with the user leaving your
* activity. Most importantly, any changes made by the user should at this
* point be committed (usually to the
* {@link android.content.ContentProvider} holding the data).
* </ul>
譯為:onCreate 用於初始化 Activity,通常在此調用 setContentView(int) 定義 UI,並用 findViewById 取出需要編程交互的控件;onPause 則是處理用戶離開時的方法,用戶操作產生的任何改動都應在此提交。
初讀之下會得出「在 onPause 中用 ContentProvider 保存」的結論,但 ContentProvider 的定位是跨應用共享數據,用於此處顯然並不合適。繼續往下讀:
Because of this, you should use the onPause method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate if the activity needs to be re-created. Note that it is important to save persistent data in onPause instead of onSaveInstanceState because the later is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
這段註釋把職責劃分講得非常明確:
onPause 中寫入存儲。onSaveInstanceState(Bundle) 中保存到 Bundle,之後在 onCreate 中取回。關鍵理由: onSaveInstanceState() 不屬於生命周期回調,並非每次 Activity 進入後台都會被調用。
重寫這兩個方法即可:
// 將數據保存到 savedInstanceState 對象中,該對象會在重建 Activity 時傳遞給 onCreate 方法
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// 例如:savedInstanceState.putString("input_text", mEditText.getText().toString());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// 例如:mEditText.setText(savedInstanceState.getString("input_text"));
}
注意調用順序:必須先調用 super,因為父類實現負責自動保存各控件自身的狀態。
源碼裡有一段專門澄清這個誤解:
* <p>Do not confuse this method with activity lifecycle callbacks such as
* {@link #onPause}, which is always called when an activity is being placed
* in the background or on its way to destruction, or {@link #onStop} which is
* called before destruction. One example of when {@link #onPause} and
* {@link #onStop} is called and not this method is when a user navigates back
* from activity B to activity A: there is no need to call
* {@link #onSaveInstanceState} on B because that particular instance will
* never be restored, so the system avoids calling it. An example when
* {@link #onPause} is called and not {@link #onSaveInstanceState} is when
* activity B is launched in front of activity A: the system may avoid calling
* {@link #onSaveInstanceState} on activity A if it isn't killed during the
* lifetime of B since the state of the user interface of A will stay intact.
邏輯其實很務實:如果系統確定某個實例永遠不會被恢復,那就沒有必要浪費資源去保存它的狀態。具體來說——用戶從 B 返回 A 時,B 的實例不會再被恢復,所以系統不調用 B 的 onSaveInstanceState;B 啟動覆蓋在 A 之上時,若 A 在 B 的整個生命周期內都沒被殺死,其界面狀態完好無損,系統也不調用 A 的 onSaveInstanceState。
onSaveInstanceState() 一定執行,隨後 onRestoreInstanceState() 也一定執行。一、默認的自動保存。即使你不重寫 onSaveInstanceState(),系統仍會自動保存 Activity 中部分 UI 控件的狀態與值——前提是該控件必須指定唯一的 android:id。這也是為什麼很多時候「什麼都沒做,旋轉後 EditText 裡的文字卻還在」。沒有 id 的控件則不會被保存。
二、兩個方法不一定成對調用。onRestoreInstanceState() 被調用的前提是 Activity 確實被系統銷毀並重建。如果只是「有這種可能性」而最終沒有銷毀,該方法不會執行。例如正在顯示 A 時按下 HOME 回到主界面,緊接著又立刻返回 A——A 一般不會因內存壓力被銷毀,所以 onRestoreInstanceState() 不會被調用。因此恢復邏輯放在 onCreate 中判斷 savedInstanceState != null 往往更穩妥。
保存到哪裡?瞬態數據用系統提供的 onSaveInstanceState(),重寫並補充系統不會自動保存的內容;需要長期存儲的則使用數據庫、文件或 SharedPreferences,緩存可放 cache 目錄。最理想的做法是結合使用,並依據各自優缺點做權衡。
為什麼 onPause 不適合存耗時數據?因為 onPause 的執行會阻塞下一個 Activity 的啟動直至其完全加載,在里面做網絡請求或大文件寫入會造成切換頁面時的明顯卡頓。耗時的持久化應該異步處理。
例子怎麼寫?最簡單的方式就是寫一個屏幕旋轉場景,在 onSaveInstanceState 中存下 EditText 的內容,在 onCreate 中恢復,跑一遍就能直觀理解。
Android Studio 設定碼提示自動彈出:告別 Eclipse 時代的手動快捷鍵
用 Eclipse 時,我們可以調整設定讓打字打到任何字母都自動跳出候選清單。Android Studio 同樣做得到,而且設定步驟更直觀。如果你覺得過度依賴自動補全会削
Android ListView 基礎入門:版面、Adapter 與複用優化
ListView 簡介ListView 是 Android 中非常常見的列表控制項,適合用來展示大量資料。它的核心概念是透過 Adapter 將資料綁定到列表,再利用 I
深入 dex 與 odex:文件結構、驗證與優化流程剖析
一、dex 文件結構 從邏輯上可把 dex 檔切成三個區塊:頭部(header)、索引區與數據區。索引區中以 ids 為後綴的字段,是 identifiers 的縮寫。
Android Studio 教程(二):基本設置與運行
上一節介紹了 Studio 的優點與安裝上手,沒想到 Google 更新如此之快,很快又推出了修復 bug 的新版本。今天這篇就帶大家預覽 Studio 的界面與基本功能