對於Android來說傳遞復雜類型,主要是將自己的類轉換為基礎的字節數組,Activity之間傳遞數據是通過Intent實現的。 Android序列化對象主要有兩種方法,實現Serializable接口、或者實現Parcelable接口。實現Serializable接口是Java
SE本身就支持的,而Parcelable是Android特有的功能,效率比實現Serializable接口高,而且還可以用在進程間通信(IPC)中。實現Serializable接口非常簡單,聲明一下就可以瞭。而實現Parcelable接口稍微復雜一些,但效率更高,推薦用這種方法提高性能。
Parcelable接口的作用:實現瞭Parcelable接口的實例可以將自身的狀態信息(狀態信息通常指的是各成員變量的值)寫入Parcel,也可以從Parcel中恢復其狀態。
Parcel用來完成數據的序列化傳遞。下面就介紹一下實現Parcelable接口的方法。
通過實現Parcelable接口序列化對象的步驟:
1、實現Parcelable接口。
2、並且實現Parcelable接口的public
void writeToParcel(Parcel dest, int flags)方法 。
3、自定義類型中必須含有一個名稱為CREATOR的靜態成員,該成員對象要求實現Parcelable.Creator接口及其方法。
簡而言之:通過writeToParcel將你的對象映射成Parcel對象,再通過createFromParcel將Parcel對象映射成你的對象。也可以將Parcel看成是一個流,通過writeToParcel把對象寫到流裡面,在通過createFromParcel從流裡讀取對象,隻不過這個過程需要你來實現,因此寫的順序和讀的順序必須一致。
示例代碼:
[java]
1. package com.yang.domain;
2.
3. import android.os.Parcel;
4. import android.os.Parcelable;
5.
6. public class Person implements Parcelable {
7. //這裡定義瞭兩個變量來說明讀和寫的順序要一致
8. private Integer id;
9. private String name;
10.
11. public Person() {
12. }
13.
14. public Person(Integer id, String name) {
15.
16. this.id = id;
17. this.name = name;
18. }
19.
20. public Integer getId() {
21. return id;
22. }
23.
24. public void setId(Integer id) {
25. this.id = id;
26. }
27.
28. public String getName() {
29. return name;
30. }
31.
32. public void setName(String name) {
33. this.name = name;
34. }
35.
36. @Override
37. public int describeContents() {
38. return 0;
39. }
40.
41. @Override
42. public void writeToParcel(Parcel dest, int flags) {
43. // 把javanbean中的數據寫到Parcel。先寫id然後寫name
44. dest.writeInt(this.id);
45. dest.writeString(this.name);
46. }
47.
48. // 添加一個靜態成員,名為CREATOR,該對象實現瞭Parcelable.Creator接口
49. public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
50. @Override
51. public Person createFromParcel(Parcel source) {
52. // 從Parcel中讀取數據,返回person對象
53. return new Person(source.readInt(), source.readString());
54. }
55.
56. @Override
57. public Person[] newArray(int size) {
58. return new Person[size];
59. }
60. };
61. }
註:Parcelable接口在Android當中有非常之多的子類,如下截圖:
並且Intent當中也定義瞭很多關於Parcelable的get、set方法,如:
Intent | putExtra(String name, Parcelable value) Add extended data to the intent. |
<T extends Parcelable> T | getParcelableExtra(String name) Retrieve extended data from the intent. |
並且Intent本身也實現瞭Parcelable接口,因此在Android開發當中是非常推薦以Parcelable作為工具傳遞復制對象。
摘自 Snowball