我正在尝试让几个不同包中的服务共享一个公共对象。每个服务都必须调用相同的对象。
例如,服务A(来自APK A)实例化了一个自定义对象,我希望服务B和C(来自APK B和C)检索此对象的引用并调用其某些方法。
我在Android参考文献中发现可以使用Parcel实现这一点:
活动对象
Parcel 的一个不寻常的特性是能够读取和写入活动对象。对于这些对象,实际对象的内容并没有被写入,而是写入一个特殊的标记引用该对象。从 Parcel 中读取对象时,您不会得到该对象的新实例,而是得到一个操作最初写入的完全相同对象的句柄。有两种类型的活动对象可用。
Binder 对象是 Android 通用跨进程通信系统的核心设施。IBinder 接口描述了一个带有 Binder 对象的抽象协议。任何此类接口都可以写入到 Parcel 中,在读取时,您将收到实现该接口的原始对象或一个特殊代理实现,该代理实现将调用返回到原始对象。要使用的方法包括 writeStrongBinder(IBinder)、writeStrongInterface(IInterface)、readStrongBinder()、writeBinderArray(IBinder[])、readBinderArray(IBinder[])、createBinderArray()、writeBinderList(List)、readBinderList(List)、createBinderArrayList()。
我尝试通过 AIDL 将我的对象(继承自 Binder)传递,但什么都不起作用,当我尝试从方法 createFromParcel(Parcel in) 中检索引用时,总是会出现 ClassCastException。
我的代码示例:public class CustomObject extends Binder implements Parcelable {
public CustomObject() {
super();
}
public static final Parcelable.Creator<CustomObject> CREATOR = new Parcelable.Creator<CustomObject>() {
public CustomObject createFromParcel(Parcel in) {
IBinder i = in.readStrongBinder();
// HOW TO RETRIEVE THE REFERENCE ??
return null;
}
@Override
public CustomObject[] newArray(int size) {
return null;
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStrongBinder(this);
}
}
有人已经完成了吗?
提前致谢!