Parcelable 和Bundle 不是专有概念;您甚至可以同时在您的应用程序上部署两者。
[1] 术语Parcelable 带有Java 中的序列化概念(以及其他高级语言,如C#、Python 等)。它确保可以将此类 Parcelable 类的对象(保留在 RAM 存储中)保存在文件流中,例如文本或内存(离线状态),然后可以重构以在程序中使用运行时(在线状态)。
在 Android 应用程序中,在 2 个 independent activities 内(仅运行 - 一个启动,然后另一个必须停止):
当前活动不会有指向前一个活动及其成员的指针 - 因为前一个活动已停止并清除了表单内存;为了维护传递给下一个活动的对象值(从Intent 调用),对象需要是parcelable (serializable)。
[2]而Bundle通常是Android的概念,表示一个变量或一组变量。再往下看,可以认为是键值对的HashMap。
结论:
[已更新] - 示例:
//Class without implementing Parcelable will cause error
//if passing though activities via Intent
public class NoneParcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public NoneParcelable()
{
nameList.add("abc");
nameList.add("xyz");
}
}
//Parcelable Class's objects can be exchanged
public class GoodParcelable implements Parcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public GoodParcelable()
{
nameList.add("Can");
nameList.add("be parsed");
}
@Override
public int describeContents()
{
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags)
{
// Serialize ArrayList name here
}
}
在源活动中:
NoneParcelable nonePcl = new NoneParcelable();
GoodParcelable goodPcl = new GoodParcelable();
int count = 100;
Intent i = new Intent(...);
i.putExtra("NONE_P",nonePcl);
i.putExtra("GOOD_P",goodPcl);
i.putExtra("COUNT", count);
在目标活动中:
Intent i = getIntent();
//this is BAD:
NoneParcelable nP = (NoneParcelable)i.getExtra("NONE_P"); //BAD code
//these are OK:
int count = (int)i.getExtra("COUNT");//OK
GoodParcelable myParcelableObject=(GoodParcelable)i.getParcelableExtra("GOOD_P");// OK