gpt4 book ai didi

java - 是否可以通过广播接收器在 Android 应用程序之间传递自定义对象?

转载 作者:行者123 更新时间:2023-11-30 10:17:47 24 4
gpt4 key购买 nike

假设有 2 个 Android 应用程序,A 和 B,B 希望将 Android 应用程序 A 中定义的自定义对象传递给 A 中定义的广播接收器,后者接受一个额外的并将其转换为自定义对象如下所示。

public void onReceive(Context paramContext, Intent Intent ){
...
paramIntent = (CustomClass)intent.getSerializableExtra("msg_bean");

假设广播接收器被导出,我尝试在 App B 中定义自定义类,以便我可以在 B 中实例化它并像这样将其广播到接收器:

    CustomClass bean = new CustomClass ();
intent.putExtra("msg_bean", bean);
sendBroadcast(intent);

假设 App A 有包 a.b.c,B 有包 d.e.f,我收到错误 ClassDef not found:d.e.f.CustomClass not found in App B,因为我发送给接收者的对象是路径 d.e.f.CustomClass 因为它被定义了在 App B 中。但是,在 App A 中定义的相同 CustomClass 具有路径 a.b.c.CustomClass。有什么方法可以手动定义对象 bean 的类路径,使其遵循 App A 中的类路径?(a.b.c.CustomClass)

最佳答案

Yes you can pass you need to create your bean class like this:
import android.os.Parcel;
import android.os.Parcelable;
public class CustomClass implements Parcelable {

private String name;
private int thumbNail;

public CustomClass() {
}

public CustomClass(String name, int thumbnail) {
this.name = name;
this.thumbNail = thumbnail;
}

protected CustomClass(Parcel in) {
name = in.readString();
thumbNail = in.readInt();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(thumbNail);
}

@Override
public int describeContents() {
return 0;
}

public static final Creator<CustomClass> CREATOR = new Creator<CustomClass>() {
@Override
public CustomClass createFromParcel(Parcel in) {
return new CustomClass(in);
}

@Override
public CustomClass[] newArray(int size) {
return new CustomClass[size];
}
};

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getThumbNail() {
return thumbNail;
}

public void setThumbNail(int thumbNail) {
this.thumbNail = thumbNail;
}

}

=> how to call intent in send broadcast:

CustomClass bean = new CustomClass();
intent.putExtra("msg_bean", bean);
sendBroadcast(intent);

=> How to get object in onReceive() method:
public void onReceive(Context paramContext, Intent intent) {
CustomClass bean = intent.getExtras().getParcelable("msg_bean");
}

关于java - 是否可以通过广播接收器在 Android 应用程序之间传递自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49573099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com