在 Android 中,Bundle
类提供了一种灵活的方法来存储和传递各种类型的数据。putParcelable
和 putBinder
是 Bundle
类中常用的方法,用于存储和传递不同类型的数据对象。
putParcelable
putParcelable
方法用于将实现了 Parcelable
接口的对象存储到 Bundle
中。Parcelable
接口是 Android 中的一种序列化机制,专为高效传输对象数据设计的。
使用示例:
假设有一个自定义类 MyParcelable
实现了 Parcelable
接口:
public class MyParcelable implements Parcelable {
private int mData;
public MyParcelable(int data) {
mData = data;
}
protected MyParcelable(Parcel in) {
mData = in.readInt();
}
public static final Creator<MyParcelable> CREATOR = new Creator<MyParcelable>() {
@Override
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
@Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mData);
}
}
将 MyParcelable
对象放入 Bundle
并传递给另一个 Activity
:
发送 Activity:
MyParcelable myParcelable = new MyParcelable(123);
Intent intent = new Intent(this, TargetActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("my_parcelable", myParcelable);
intent.putExtras(bundle);
startActivity(intent);
接收 Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_target);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
MyParcelable myParcelable = bundle.getParcelable("my_parcelable");
if (myParcelable != null) {
// 使用 myParcelable 对象
}
}
}
putBinder
putBinder
方法用于将实现了 IBinder
接口的对象存储到 Bundle
中。IBinder
是 Android 的跨进程通信机制,常用于 Service
和 AIDL
。
使用示例:
假设有一个自定义的 Binder
类:
public class MyBinder extends Binder {
private final MyService mService;
public MyBinder(MyService service) {
mService = service;
}
public MyService getService() {
return mService;
}
}
将 MyBinder
对象放入 Bundle
并传递给另一个 Activity
:
发送 Activity:
MyService myService = ...; // 获取 MyService 实例
MyBinder myBinder = new MyBinder(myService);
Intent intent = new Intent(this, TargetActivity.class);
Bundle bundle = new Bundle();
bundle.putBinder("my_binder", myBinder);
intent.putExtras(bundle);
startActivity(intent);
接收 Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_target);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
IBinder binder = bundle.getBinder("my_binder");
if (binder instanceof MyBinder) {
MyService myService = ((MyBinder) binder).getService();
// 使用 myService 对象
}
}
}
区别与选择
putParcelable
:用于传递实现了Parcelable
接口的对象,适合在同一进程内传递较小的、轻量级的数据对象。putBinder
:用于传递实现了IBinder
接口的对象,适合跨进程通信或在服务和活动之间传递接口或服务实例。
根据你的具体需求选择合适的方法,以确保数据传递的高效和可靠性。