Android - 通过广播接收器跨应用程序发送/接收POJO

时间:2014-09-10 03:51:50

标签: java android android-intent broadcastreceiver

我正在做两个Android应用程序。

  • 应用程序1发送一个广播,其中放入了“额外”自定义POJO。
  • 应用程序2接收广播并获取“额外”(自定义POJO)并显示它。

这是我的自定义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中使用它?

非常感谢任何帮助或建议。非常感谢你。

1 个答案:

答案 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");
    }
}

要传递数据,请将其作为可序列化的附加内容传递给你,你应该好好去。

希望它有所帮助。

相关问题