我正在做两个Android应用程序。
这是我的自定义POJO,它实现了Parcelable
package com.steven.app1;
public class Customer implements Parcelable {
private int id;
private String firstName;
private String lastName;
public static final Parcelable.Creator<Customer> CREATOR = new Parcelable.Creator<Customer>() {
public Customer createFromParcel(Parcel in) {
return new Customer(in);
}
public Customer[] newArray(int size) {
return new Customer[size];
}
};
public Customer(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public Customer(Parcel source) {
id = source.readInt();
firstName = source.readString();
lastName = source.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(firstName);
dest.writeString(lastName);
}
}
应用程序1然后像这样广播
Intent i = new Intent("com.steven.app1.RECEIVE_CUSTOMER");
i.putExtra("customer", customer);
sendBroadcast(i);
在应用程序2中,我会像这样收到应用程序1的广播
package com.steven.app2;
public class CustomerBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Customer customer = (Customer) data.getParcelable("customer");
}
}
}
我在第
行收到错误Customer customer = (Customer) data.getParcelable("customer");
因为Application 2没有Customer类
因此,我复制了Application 1的Customer类并将其粘贴到Application 2源中以删除错误。但运行应用程序2后,显示此错误。
“解组时找不到类:com.steven.app1.Customer”
那么我如何获得Application 1中的Customer类并在Application 2中使用它?
非常感谢任何帮助或建议。非常感谢你。
答案 0 :(得分:0)
获取 Customer 类并将其放入可由2个应用程序项目引用的库项目中。然后,为了使您更容易实现 Customer 类中的 Serializable 接口。类似的东西:
public class Customer implements Serializable{
/**
* Auto generated
*/
private static final long serialVersionUID = -559996182231809327L;
private int id;
private String firstName;
private String lastName;
public Customer(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
// Add getters/setters here
}
这将是一个更加简单和清洁的解决方案。
您的 onReceive(..)方法应如下所示:
@Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Customer customer = (Customer) data.getSerializable("customer");
}
}
要传递数据,请将其作为可序列化的附加内容传递给你,你应该好好去。
希望它有所帮助。