Android中的序列化淺析_Android

來源:互聯網
上載者:User

序列化原因

序列化的原因基本可以歸納為以下三種情況:

1.永久性儲存對象,儲存對象的位元組序列到本地檔案中;
2.對象在網路中傳遞;
3.對象在IPC間傳遞。

序列化方法

在Android系統中關於序列化的方法一般有兩種,分別是實現Serializable介面和Parcelable介面,其中Serializable介面是來自Java中的序列化介面,而Parcelable是Android內建的序列化介面。

上述的兩種序列化介面都有各自不同的優缺點,我們在實際使用時需根據不同情況而定。


1.Serializable在序列化的時候會產生大量的臨時變數,從而引起頻繁的GC,而相比之下Parcelable的效能更高(畢竟是Android內建的),所以當在使用記憶體時(如:序列化對象在網路中傳遞對象或序列化在進程間傳遞對象),更推薦使用Parcelable介面。

2.但Parcelable有個明顯的缺點:不能能使用在要將資料存放區在磁碟上的情況(如:永久性儲存對象,儲存對象的位元組序列到本地檔案中),因為Parcel本質上為了更好的實現對象在IPC間傳遞,並不是一個通用的序列化機制,當改變任何Parcel中資料的底層實現都可能導致之前的資料不可讀取,所以此時還是建議使用Serializable 。

代碼實現

Serializable介面的實現及使用

Serializable的介面實現很簡單,只需讓需要序列化的類繼承Serializable 即可,系統會自動將其序列化,具體代碼如下:

public class Book implements Serializable {  private static final long serialVersionUID = 21455356667888L;  private String mName;  private String mPrice;  public String getmName() {    return mName;  }  public void setmName(String mName) {    this.mName = mName;  }  public String getmPrice() {    return mPrice;  }  public void setmPrice(String mPrice) {    this.mPrice = mPrice;  }}

在Activity中使用方法:

// serializable對象傳遞方法public void setSerializableMethod() {  Book book = new Book();  book.setmName("王海康");  book.setmPrice("20$");  Intent intent = new Intent(this, BookTest.class);  Bundle bundle = new Bundle();  bundle.putSerializable(SER_KEY, book);  intent.putExtras(bundle);  startActivity(intent);}// serializable對象擷取方法public Book getSerializableMethod(){  Book mBook = (Book )getIntent().getSerializableExtra(SER_KEY);  return mBook;}

Parcelable介面的實現及使用

實現Parcelable介面主要可以分為一下幾步:
1)implements Parcelable。
2)重寫writeToParcel方法,將你的對象序列化為一個Parcel對象,即:將類的資料寫入外部提供的Parcel中,打包需要傳遞的資料到Parcel容器儲存,以便從Parcel容器擷取資料。
3)重寫describeContents方法,內容介面描述,預設返回0即可。
4)執行個體化靜態內部對象CREATOR實現介面Parcelable.Creator 。
注意:若將Parcel看成是一個流,則先通過writeToParcel把對象寫到流裡面,再通過createFromParcel從流裡讀取對象,因此類實現的寫入順序和讀出順序必須一致。
具體實現代碼如下:

public class Person implements Parcelable {  private String mName;  private String mSex;  private int mAge;  public String getmName() {    return mName;  }  public void setmName(String mName) {    this.mName = mName;  }  public String getmSex() {    return mSex;  }  public void setmSex(String mSex) {    this.mSex = mSex;  }  public int getmAge() {    return mAge;  }  public void setmAge(int mAge) {    this.mAge = mAge;  }  @Override  public int describeContents() {    return 0;  }  @Override  public void writeToParcel(Parcel dest, int flags) {    dest.writeString(mName);    dest.writeString(mSex);    dest.writeInt(mAge);  }  public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() {    @Override    public Person createFromParcel(Parcel source) {      Person person = new Person();      person.mName = source.readString();      person.mSex = source.readString();      person.mAge = source.readInt();      return person;    }    //供還原序列化本類數組時調用的    @Override    public Person[] newArray(int size) {      return new Person[size];    }  };

在Activity中使用方法:

1)傳遞單一對象,具體代碼如下:

// parcelable對象傳遞方法public void setParcelableMethod() {  Person person = new Person();  person.setmName("王海康");  person.setmSex("男");  person.setmAge(45);  Intent intent = new Intent(this, PersonTest.class);  Bundle bundle = new Bundle();  bundle.putParcelable(PAR_KEY, person);  intent.putExtras(bundle);  startActivity(intent);}// parcelable對象擷取方法public Person getParcelableMethod(){  Person mPerson = (Person)getIntent().getParcelableExtra(PAR_KEY);  return mPerson;}

2)傳遞對象列表,具體代碼如下:
需要注意的是,若List personList = new ArrayList();則會報錯,因為下面調用的putParcelableArrayList()函數其中一個參數的類型為ArrayList。

// parcelable對象List傳遞方法public void setParcelableListMethod() {  ArrayList<Person> personList = new ArrayList<Person>();  Person person1 = new Person();  person1.setmName("王海康");  person1.setmSex("男");  person1.setmAge(45);  personList.add(person1);  Person person2 = new Person();  person2.setmName("薛嶽");  person2.setmSex("男");  person2.setmAge(15);  personList.add(person2);  Intent intent = new Intent(this, PersonTest.class);  Bundle bundle = new Bundle();  bundle.putParcelableArrayList(PAR_LIST_KEY, personList);  intent.putExtras(bundle);  startActivity(intent);}// parcelable對象擷取方法public ArrayList<Person> getParcelableMethod(){  ArrayList<Person> mPersonList = getIntent().getParcelableExtra(PAR_LIST_KEY);return mPersonList;}

3)最後介紹一個投機取巧的方法:
不用繼承Parcelable或Serializable方法即可實現IPC中對象的傳遞。這種方法的實現原理不是很明白,只知道代碼中new ArrayList()返回的其實是一個EmptyArray.OBJECT數組,不過我感覺應該還是系統調用Serializable進行序列化的,如果各位讀者有好的想法,歡迎告知。
具體代碼如下:

//對象List傳遞public void setObjectMethod(){  ......(省略)  ArrayList list = new ArrayList();  //ObjectList為某一對象列表  list.add(ObjectList);  bundle.putParcelableArrayList(PAR_LIST_KEY, list);  intent.putExtras(bundle);  startActivity(intent);}//擷取對象ListArrayList list = bundle.getParcelableArrayList("list");//強轉成你自己定義的list,這樣ObjectList就是你傳過來的那個list了。ObjectList= (List<Object>) list.get(0);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.