編輯:關於 Android 程式設計
在移動應用的架構設計中,界面與數據既不可分割又不可混淆。日常開發中我們多用 Fragment 進行界面編程,即便保存數據也往往局限於界面控件的相關數據。本文將介紹 Fragment 的一種另類用法——只用來保存數據而不含任何界面元素。
Fragment 的數據保存方法與 setRetainInstance 密切相關,其應用背景通常是屏幕旋轉或其他配置改變時的狀態保持。無論界面由 Activity 還是 Fragment 生成,屏幕旋轉時都會在 onSaveInstanceState 中緩存控件狀態與必要數據,通常使用 Bundle 存儲。正如官方介紹,Bundle 是一個用於存儲 String 及其他序列化數據類型的 map。
然而 Android 中存在這樣一個異常:TransactionTooLargeException,即傳輸數據過大異常。現行系統對應用程序的傳輸數據大小限制在 1MB 以內,因此若屏幕旋轉時用 Bundle 緩存大數據並不安全。Bitmap 就是典型代表,雖然它已序列化、便於用 Bundle 緩存,但仍強烈不建議這樣做。下面提供一個簡單的解決途徑。
首先,創建一個專門用來保存數據的 Fragment:
public class BitmapDataFragment extends Fragment {
public static final String TAG = "bitmapsaver";
private Bitmap bitmap;
private BitmapDataFragment(Bitmap bitmap) {
this.bitmap = bitmap;
}
public static BitmapDataFragment newInstance(Bitmap bitmap) {
return new BitmapDataFragment(bitmap);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public Bitmap getData() {
return bitmap;
}
}
這個 Fragment 沒有任何界面,並在 onCreate 中調用 setRetainInstance(true),確保它不會隨載體銷毀,從而保障數據安全。
使用時,假設載體是 Activity,在 onSaveInstanceState 中把數據放入 Fragment:
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mBitmap != null) {
getSupportFragmentManager().beginTransaction()
.add(BitmapDataFragment.newInstance(mBitmap), BitmapDataFragment.TAG)
.commit();
outState.putBoolean(SENSE_IMAGE_KEY, true);
} else {
outState.putBoolean(SENSE_IMAGE_KEY, false);
}
super.onSaveInstanceState(outState);
}
設備旋轉時,檢測當前界面顯示的 Bitmap,若確有數據,就 new 一個 Fragment 把 Bitmap 放進去,添加到 FragmentManager 並指定 tag,這樣恢復狀態後便能輕松找到它。
恢復時,在 onCreate 中透過 Bundle 判斷是否有數據待取:
if (savedInstanceState.getBoolean(SENSE_IMAGE_KEY)) {
BitmapDataFragment fragment = (BitmapDataFragment) getSupportFragmentManager()
.findFragmentByTag(BitmapDataFragment.TAG);
bitmap = fragment.getData();
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}
提醒:取出 Bitmap 後,別忘了把這個作為數據容器的 Fragment 從 FragmentManager 中移除,以釋放其占用的系統內存。
所謂「非中斷保存」,是指保持原有 Fragment 中的對象或動作不被中斷。由於 Fragment 依附於 Activity,當 Activity 因配置改變(如屏幕旋轉)而被銷毀重建時,Fragment 也會隨之銷毀重建,新生成的 Fragment 中對象與之前並不相同。若想在 Activity 重組時保持原 Fragment 的對象與動作,就需要非中斷式保存。
Activity 在配置改變時的生命周期為:onPause → onStop → onDestroy → onStart → onResume。在 onDestroy 中,Activity 默認會銷毀 FragmentManager 所包含的所有 Fragment,此時 Fragment 的生命周期為:onDestroyView → onDestroy → onDetach。
透過查看 FragmentManager 源碼可以發現,當 Fragment 的 mRetaining 被置為 true 時,onDestroy 並不會真正執行銷毀邏輯。而 mRetaining 狀態由 retainNonConfig() 配置,其條件是 Fragment 不為空且 mRetainInstance 為 true。也就是說,只要讓 mRetainInstance 為 true,就能避免 Fragment 被銷毀。
Fragment.java 中 setRetainInstance 的官方注釋對這一機制有清晰說明:
/**
* Control whether a fragment instance is retained across Activity
* re-creation (such as from a configuration change). This can only
* be used with fragments not in the back stack. If set, the fragment
* lifecycle will be slightly different when an activity is recreated:
* - onDestroy() will not be called (but onDetach() still will be).
* - onCreate(Bundle) will not be called since the fragment is not being re-created.
* - onAttach(Activity) and onActivityCreated(Bundle) will still be called.
*/
public void setRetainInstance(boolean retain) {
if (retain && mParentFragment != null) {
throw new IllegalStateException("Can't retain fragements that are nested in other fragments");
}
mRetainInstance = retain;
}
總結來說:設置 setRetainInstance(true) 後,一旦 Activity 重組,Fragment 會跳過 onDestroy 直接進入 onDetach(界面消失、對象尚存),重組時也會跳過 onCreate,而 onAttach 與 onActivityCreated 仍會被調用。需要注意的是,使用這種方式的 Fragment 不能加入 backstack 後退棧,且被保存的 Fragment 實例不會保持太久,若長時間沒有容器承載,也會被系統回收。
這是 Fragment 的一種非主流用法,相比直接用 Bundle 保存數據確實稍顯複雜,但能更安全地進行數據轉移,對應用而言仍是非常值得的選擇,推薦指數五顆星。
Android Socket 即時通訊實戰:從服務端到客戶端一次打通
Socket 建立在 TCP 協議之上,特別適合長連接的場景。要做一個完整的 Socket 通訊,自然離不開客戶端與服務端這兩端:客戶端我們放在 Android 上編寫,
Android 非同步 HTTP 框架解析與原理實作
前面幾篇已經談過 Android 提交資料到伺服器的幾種方式,包括 get、post 以及使用 HttpClient。本文換個角度,介紹以 android-async-h
Android 必備知識:Fragment 使用、參數傳遞與宿主通訊
Fragment 是 Android 中用來表示 Activity 中一部分介面的元件。它可以被多個 Activity 重用,也可以在同一個 Activity 中組合多個
Android 原生 JSON 解析的三個層次:JSONObject、JSONArray 與多層巢狀
最近專案裡要做一个天氣預覽頁,欄位多、資料層級也深,索性整理成一篇筆記,對自己複習、對讀者也有幫助。另外提醒:只要涉及網路,記得先在 AndroidManifest 加上