Android開發之Parcel機制執行個體分析_Android

來源:互聯網
上載者:User

本文執行個體講述了Android開發之Parcel機制。分享給大家供大家參考。具體分析如下:

在java中,有序列化機制。但是在安卓裝置上,由於記憶體有限,所以設計了新的序列化機制。

Container for a message (data and object references) that can be sent through an IBinder.  A Parcel can contain both flattened data that will be unflattened on the other side of the IPC (using the various methods here for writing specific types, or the generalParcelable interface), and references to liveIBinder objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel.

Parcel is not a general-purpose serialization mechanism.  This class (and the correspondingParcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport.  As such, it is not appropriate to place any Parcel data in to persistent storage: changes in the underlying implementation of any of the data in the Parcel can render older data unreadable.

從上面的官方解釋可以看到,Parcel主要就是用來序列化,在一端編碼,在另外一端進行解碼。

本質上把它當成一個Serialize就可以了,只是它是在記憶體中完成的序列化和還原序列化,利用的是連續的記憶體空間,因此會更加高效。

我們接下來要說的是Parcel類如何應用。就應用程式而言,最常見使用Parcel類的情境就是在Activity間傳遞資料。沒錯,在Activity間使用Intent傳遞資料的時候,可以通過Parcelable機制傳遞複雜的對象。

具體例子可以參見這裡,寫的很好。

在實現Parcelable介面的時候,必須實現其中的兩個方法並且定義一個CREATOR:

@Override public int describeContents() {    return 0; } @Override public void writeToParcel(Parcel dest, int flags) {    dest.writeInt(color); }

其中,writeToParcel方法定義了怎麼向序列化中寫入該類對象的資訊。

CREATOR對象中定義了兩個函數:

public MyColor createFromParcel(Parcel in) {  return new MyColor(in);}public MyColor[] newArray(int size) {  return new MyColor[size];}

其中,createFromParcel方法告訴平台如何從已經序列化的對象中構建該類的執行個體。newArray方法的作用不明。實現於Parcelable介面的CREATOR成員的createFromParcel方法用於告訴平台如何從包裹裡建立該類的執行個體,而writeToParcel方法則用於告訴平台如何將該類的執行個體儲存到包裹中。通過這種約定,平台就知道怎麼序列化和還原序列化了。

希望本文所述對大家的Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.