public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private String firstName, lastName, address;
private int age;
public Customer(String fn, String ln, int age, String addr) {
this.firstName = fn; this.lastName = ln; this.age = age; this.address = addr;
}
// getter/setter...
}
Customer customer = new Customer("John", "Doe", 30, "123 Street");
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("customer", customer); // Serializable 自動支持
startActivity(intent);
Customer customer = (Customer) getIntent().getSerializableExtra("customer");
if (customer != null) {
textView.setText(customer.getFirstName() + " " + customer.getLastName());
}
public class Customer implements Parcelable {
// 字段...
protected Customer(Parcel in) {
firstName = in.readString();
lastName = in.readString();
age = in.readInt();
address = in.readString();
}
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeString(firstName);
dest.writeString(lastName);
dest.writeInt(age);
dest.writeString(address);
}
public static final Creator CREATOR = new Creator() {
@Override public Customer createFromParcel(Parcel in) { return new Customer(in); }
@Override public Customer[] newArray(int size) { return new Customer[size]; }
};
}
Android Studio 右鍵 Generate → Parcelable 可自動生成樣板代碼。
超過 1MB (Binder 事務緩衝區限制) 需用共享內存、文件、數據庫或 Application 单例中轉。