編輯:關於 Android 程式設計
Android 開發裡,Activity 之間傳遞資料幾乎是日常。基本型別用 putExtra 就夠,但如果要傳的是自訂物件,就必須先讓它「可序列化」。Android 支援兩套機制:java.io.Serializable 與 android.os.Parcelable。
兩者的差異在哪?
1. 記憶體使用效率上,Parcelable 明顯優於 Serializable,官方也推薦首選 Parcelable;
2. Serializable 在序列化過程會產生大量臨時物件,容易觸發頻繁的 GC,造成效能抖動;
3. Parcelable 是把物件寫進 Parcel 這塊共享記憶體,設計上就是給「進程間傳遞」用的,並不適合持久化到磁碟。若你需要把物件存成檔案長期保存,Serializable 才是正解。
一句話結論:跨 Activity / 跨進程傳遞用 Parcelable,落磁碟保存用 Serializable。
第一步:定義可序列化的實體類
Serializable 版本:
/** * PersonSer * * @author https://blog.csdn.net/zuolongsnail */ public class PersonSer implements Serializable { /** * serialVersionUID的作用是在修改實體類後,可以正常的序列化和反序列化,在此不多說,大家可以谷歌百度下。 */ private static final long serialVersionUID = -7620435178023928252L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Parcelable 版本,需要手寫 CREATOR 與 writeToParcel:
/** * PersonPar * * @author https://blog.csdn.net/zuolongsnail */ public class PersonPar implements Parcelable { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } /** * 序列化實體類 */ public static final Parcelable.Creator<PersonPar> CREATOR = new Creator<PersonPar>() { public PersonPar createFromParcel(Parcel source) { PersonPar personPar = new PersonPar(); personPar.name = source.readString(); personPar.age = source.readInt(); return personPar; } public PersonPar[] newArray(int size) { return new PersonPar[size]; } }; @Override public int describeContents() { return 0; } /** * 將實體類數據寫入Parcel */ @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(name); parcel.writeInt(age); } }
要注意 Parcelable 欄位的讀取順序必須和寫入順序完全一致,這是新手最常犯的錯誤之一。
第二步:封裝進 Bundle 並發送
Intent intent = new Intent(MainActivity.this, DestActivity.class); Bundle bundle = new Bundle(); switch (v.getId()) { case R.id.serializable_btn: // Serializable傳遞對象 PersonSer personSer = new PersonSer(); personSer.setName("zuolong"); personSer.setAge(26); bundle.putSerializable(SER_KEY, personSer); intent.putExtra("type", SER_TYPE); intent.putExtras(bundle); startActivity(intent); break; case R.id.parcelable_btn: // Parcelable傳遞對象 PersonPar personPar = new PersonPar(); personPar.setName("snail"); personPar.setAge(27); // Bundle有putParcelableArray和putParcelableArrayList方法,也就可以傳遞數組和列表 bundle.putParcelable(PAR_KEY, personPar); intent.putExtra("type", PAR_TYPE); // Intent也有putParcelableArrayListExtra方法,可以傳遞實現Parcelable接口的對象列表 intent.putExtras(bundle); startActivity(intent); break; }
如果要傳集合,Parcelable 有 putParcelableArrayList,Intent 也有 putParcelableArrayListExtra,直接可用的 API 比 Serializable 友善得多。
第三步:在目標 Activity 取值
StringBuffer sb = new StringBuffer(); String type = getIntent().getStringExtra("type"); // 根據type判斷是哪種類型 if (type.equals(MainActivity.SER_TYPE)) { // 獲取Serializable對象 PersonSer personSer = (PersonSer) getIntent().getSerializableExtra( MainActivity.SER_KEY); sb.append("----From Serializable----").append("\n"); sb.append("Name:").append(personSer.getName()).append("\n"); sb.append("Age:").append(personSer.getAge()).append("\n"); } else if (type.equals(MainActivity.PAR_TYPE)) { // 獲取Parcelable對象 PersonPar personPar = (PersonPar) getIntent().getParcelableExtra( MainActivity.PAR_KEY); sb.append("----From Parcelable----").append("\n"); sb.append("Name:").append(personPar.getName()).append("\n"); sb.append("Age:").append(personPar.getAge()).append("\n"); }
執行結果如下圖:

最後提醒一個實務細節:以 Bundle 傳遞時,Activity 重建(例如旋轉螢幕)後 Bundle 會被系統保存下來,因此 Parcelable 實作一定要正確,否則重建時會拿到錯誤資料或直接崩潰。現在的 Jetpack 也提供了 @Parcelize 註解,Kotlin 專案可以省掉手寫 CREATOR 的麻煩。
感謝閱讀,希望對大家有幫助。
Android 四大元件之 Service 篇
以前我總覺得四大元件裡的 Service 和 BroadcastReceiver 用得少,其實不然,只是因為它們比較抽象,總是默默無聞地在後台提供服務。 我寫了個 dem
Android 網絡編程全景總結:從 HTTP 到 Socket 與服務器推送
概述 在正式動手之前,先釐清幾個基礎問題。 1)Android 平台有哪些網絡相關的 API? a) java.net.*(標準 Java 接口) 這個包提供了大量與聯
Android 實戰:用 Volley + GSON 做一個英文詞典查詢
上一節我們用 GSON 解析了接口返回的 JSON,這一節把它真正做成一個能用的功能——英文單詞查詢。先複習一下接口返回的數據結構: 一、按層次建立數據模型 這個接口
用 Activity 打造圓角自訂彈窗的技巧
要讓彈窗呈現圓角外觀,關鍵在於準備一張 9-patch 背景圖。開啟 SDK 目錄下的 tools 資料夾,雙擊 draw9patch.bat 即可啟動繪圖工具,如下圖所