1.Serializable(不推荐)
实现要点:类继承Serializable接口
举例:MainActivity通过Intent跳转到SubActivity的时候传递Test类实例test。
MainActivity.java
Intent intent = new Intent(MainActivity.this, SubActivity.class);
Test test = new Test();
test.name = "hello";
intent.putExtra("test", test);
startActivity(intent);
SubActivity.java
Intent intent = getIntent();
Test test = (Test)intent.getSerializableExtra("test");
Test.java
public class Test implements Serializable
{
public String name;
}
2.Parcelable(推荐)
实现要点:
类继承Parcelable接口,且需要实现三个东西
1)writeToParcel 方法。
2)describeContents方法。
3)静态的Parcelable.Creator接口,有两个方法:
createFromParcel(Parcel in)
newArray(int size)
举例:MainActivity通过Intent跳转到SubActivity的时候传递Test类实例test。
MainActivity.java(同上)
Intent intent = new Intent(MainActivity.this, SubActivity.class);
Test test = new Test();
test.name = "hello";
intent.putExtra("test", test);
startActivity(intent);
SubActivity.java
Intent intent = getIntent();
Test test = intent.getParcelableExtra("test");
Test.java
public class Test implements Parcelable
{
public String name;
@Override
public int describeContents()
{
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(name);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator()
{
public Test createFromParcel(Parcel in)
{
Test test = new Test();
test.name = in.readString();
return test;
}
public Test[] newArray(int size)
{
return new Test[size];
}
};
}
3.其他有用信息
Parcelable的性能比Serializable好,在内存开销方面较小,所以在内存间数据传输时推荐使用Parcelable,如activity间传输数据,而Serializable可将数据持久化方便保存,所以在需要保存或网络传输数据时选择Serializable。