android中Parcelable接口的使用

来源:互联网 发布:数据分析入门书籍 编辑:程序博客网 时间:2024/05/29 09:13

一、理解

Parcelable是一个接口、用来实现序列化。与此类似的还有一个接口Serializable,这是JavaSE本身支持的,而Parcelable是android特有的。二者比较:

1、Parcelable使用起来稍复杂点,而后者使用起来非常简单。下面例子中会看到。

2、Parcelable效率比Serializable高,支持Intent数据传递,也支持进程间通信(IPC)。

3、Parcelable使用时要用到一个Parcel,可以简单将其看为一个容器,序列化时将数据写入Parcel,反序列化时从中取出。

4、在使用内存的时候,Parcelable比Serializable性能高,所以推荐使用Parcelable。Serializable在序列化的时候会产生大量的临时变量,从而引起频繁的GC。Parcelable不能使用在要将数据存储在磁盘上的情况,因为Parcelable在外界有变化的情况下不能很好的保证数据的持续性。尽管Serializable效率低点,但此时还是建议使用Serializable 。

二、源码

结合源码及注释进行理解:

  1. package android.os;  
  2.   
  3. /** 
  4.  * Interface for classes whose instances can be written to 
  5.  * and restored from a {@link Parcel}.  Classes implementing the Parcelable 
  6.  * interface must also have a static field called <code>CREATOR</code>, which 
  7.  * is an object implementing the {@link Parcelable.Creator Parcelable.Creator} 
  8.  * interface. 
  9.  *  
  10.  * <p>A typical implementation of Parcelable is:</p> 
  11.  *  
  12.  * <pre> 
  13.  * public class MyParcelable implements Parcelable { 
  14.  *     private int mData; 
  15.  * 
  16.  *     public int describeContents() { 
  17.  *         return 0; 
  18.  *     } 
  19.  * 
  20.  *     public void writeToParcel(Parcel out, int flags) { 
  21.  *         out.writeInt(mData); 
  22.  *     } 
  23.  * 
  24.  *     public static final Parcelable.Creator<MyParcelable> CREATOR 
  25.  *             = new Parcelable.Creator<MyParcelable>() { 
  26.  *         public MyParcelable createFromParcel(Parcel in) { 
  27.  *             return new MyParcelable(in); 
  28.  *         } 
  29.  * 
  30.  *         public MyParcelable[] newArray(int size) { 
  31.  *             return new MyParcelable[size]; 
  32.  *         } 
  33.  *     }; 
  34.  *      
  35.  *     private MyParcelable(Parcel in) { 
  36.  *         mData = in.readInt(); 
  37.  *     } 
  38.  * }</pre> 
  39.  */  
  40. public interface Parcelable {  
  41.     /** 
  42.      * Flag for use with {@link #writeToParcel}: the object being written 
  43.      * is a return value, that is the result of a function such as 
  44.      * "<code>Parcelable someFunction()</code>", 
  45.      * "<code>void someFunction(out Parcelable)</code>", or 
  46.      * "<code>void someFunction(inout Parcelable)</code>".  Some implementations 
  47.      * may want to release resources at this point. 
  48.      */  
  49.     public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001;  
  50.       
  51.     /** 
  52.      * Bit masks for use with {@link #describeContents}: each bit represents a 
  53.      * kind of object considered to have potential special significance when 
  54.      * marshalled. 
  55.      */  
  56.     public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001;  
  57.       
  58.     /** 
  59.      * Describe the kinds of special objects contained in this Parcelable's 
  60.      * marshalled representation. 
  61.      *   
  62.      * @return a bitmask indicating the set of special object types marshalled 
  63.      * by the Parcelable. 
  64.      */  
  65.     public int describeContents();  
  66.       
  67.     /** 
  68.      * Flatten this object in to a Parcel. 
  69.      *  
  70.      * @param dest The Parcel in which the object should be written. 
  71.      * @param flags Additional flags about how the object should be written. 
  72.      * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}. 
  73.      */  
  74.     public void writeToParcel(Parcel dest, int flags);  
  75.   
  76.     /** 
  77.      * Interface that must be implemented and provided as a public CREATOR 
  78.      * field that generates instances of your Parcelable class from a Parcel. 
  79.      */  
  80.     public interface Creator<T> {  
  81.         /** 
  82.          * Create a new instance of the Parcelable class, instantiating it 
  83.          * from the given Parcel whose data had previously been written by 
  84.          * {@link Parcelable#writeToParcel Parcelable.writeToParcel()}. 
  85.          *  
  86.          * @param source The Parcel to read the object's data from. 
  87.          * @return Returns a new instance of the Parcelable class. 
  88.          */  
  89.         public T createFromParcel(Parcel source);  
  90.           
  91.         /** 
  92.          * Create a new array of the Parcelable class. 
  93.          *  
  94.          * @param size Size of the array. 
  95.          * @return Returns an array of the Parcelable class, with every entry 
  96.          * initialized to null. 
  97.          */  
  98.         public T[] newArray(int size);  
  99.     }  
  100.   
  101.     /** 
  102.      * Specialization of {@link Creator} that allows you to receive the 
  103.      * ClassLoader the object is being created in. 
  104.      */  
  105.     public interface ClassLoaderCreator<T> extends Creator<T> {  
  106.         /** 
  107.          * Create a new instance of the Parcelable class, instantiating it 
  108.          * from the given Parcel whose data had previously been written by 
  109.          * {@link Parcelable#writeToParcel Parcelable.writeToParcel()} and 
  110.          * using the given ClassLoader. 
  111.          * 
  112.          * @param source The Parcel to read the object's data from. 
  113.          * @param loader The ClassLoader that this object is being created in. 
  114.          * @return Returns a new instance of the Parcelable class. 
  115.          */  
  116.         public T createFromParcel(Parcel source, ClassLoader loader);  
  117.     }  
  118. }  

三、示例

Student:

  1. package com.home.testparcelable;  
  2.   
  3. import android.os.Parcel;  
  4. import android.os.Parcelable;  
  5.   
  6. public class Student implements Parcelable {  
  7.     private int id;  
  8.     private String name;  
  9.   
  10.     public Student() {  
  11.         super();  
  12.     }  
  13.   
  14.     public Student(int id, String name) {  
  15.         super();  
  16.         this.id = id;  
  17.         this.name = name;  
  18.     }  
  19.   
  20.     public int getId() {  
  21.         return id;  
  22.     }  
  23.   
  24.     public void setId(int 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.         // 序列化过程:必须按成员变量声明的顺序进行封装  
  44.         dest.writeInt(id);  
  45.         dest.writeString(name);  
  46.     }  
  47.   
  48.     // 反序列过程:必须实现Parcelable.Creator接口,并且对象名必须为CREATOR  
  49.     // 读取Parcel里面数据时必须按照成员变量声明的顺序,Parcel数据来源上面writeToParcel方法,读出来的数据供逻辑层使用  
  50.     public static final Parcelable.Creator<Student> CREATOR = new Creator<Student>() {  
  51.   
  52.         @Override  
  53.         public Student createFromParcel(Parcel source) {  
  54.             return new Student(source.readInt(), source.readString());  
  55.         }  
  56.   
  57.         @Override  
  58.         public Student[] newArray(int size) {  
  59.             return new Student[size];  
  60.         }  
  61.     };  
  62.   
  63. }  

MainActivity:

  1. package com.home.testparcelable;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9.   
  10. public class MainActivity extends Activity {  
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.main);  
  15.         Button btn = (Button) findViewById(R.id.main_btn);  
  16.         btn.setOnClickListener(new OnClickListener() {  
  17.   
  18.             @Override  
  19.             public void onClick(View arg0) {  
  20.                 Intent in = new Intent(MainActivity.this, SecondActivity.class);  
  21.                 in.putExtra("stu", new Student(1, "张三"));  
  22.                 startActivity(in);  
  23.             }  
  24.         });  
  25.     }  
  26. }  

SecondActivity:

  1. package com.home.testparcelable;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5.   
  6. public class SecondActivity extends Activity {  
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         Student stu = getIntent().getParcelableExtra("stu");  
  11.         System.out.println("id:" + stu.getId());  
  12.         System.out.println("name:" + stu.getName());  
  13.     }  
  14. }  

 

自己实现的:

package com.yangfuhai.asimplecachedemo;

import android.annotation.SuppressLint;
import android.os.Parcel;
import android.os.Parcelable;

/***
* 实现Parcelable接口实例模型

* @author Administrator

*/
public class Test implements Parcelable {

private int noId;
private String userName;
private String address;

public Test() {
}

@SuppressLint("ParcelCreator")
public Test(int noId, String userName, String address) {
this.noId = noId;
this.userName = userName;
this.address = address;
}

public int getNoId() {
return noId;
}

public void setNoId(int noId) {
this.noId = noId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public static Creator<Test> getCreator() {
return creator;
}

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(noId);
dest.writeString(userName);
dest.writeString(address);
}

public static final Creator<Test> creator = new Creator<Test>() {

@Override
public Test createFromParcel(Parcel source) {
return new Test(source.readInt(), source.readString(),
source.readString());
}

@Override
public Test[] newArray(int size) {
return new Test[size];
}

};
}


}

原创粉丝点击