Intent的extra里又放了自定义Parcelable的in

2019-12-26  本文已影响0人  我想04

Intent里嵌套放了intent且内层intent有自定义Parcelable对象时,会报错:

ClassNotFoundException when unmarshalling:  xxx.xxx.IPCData

例子:A和B Activity甚至不用在不同进程都一样有问题
A Activity

Intent intent = new Intent(this, B.class);

Intent innerIntent = new Intent();
innerIntent.putExtra("key1", "value1");
IPCData ipcData = new IPCData();
ipcData.data = "data";
innerIntent.putExtra("data", ipcData);

intent.putExtra("intent", innerIntent);
startActivity(intent);

B Activity:

Intent intent = getIntent();
Intent innerIntent = intent.getParcelableExtra("intent");
IPCData data = innerIntent.getParcelableExtra("data");//没有这一行,只有下面一行时也一样的效果
String key1 = innerIntent.getStringExtra("key1");

IPCData:

import android.os.Parcel;
import android.os.Parcelable;

public class IPCData implements Parcelable {

    public String data;

    public IPCData(){}

    protected IPCData(Parcel in) {
        data = in.readString();
    }

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

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

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

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

解决方案:
B Activity:

Intent intent = getIntent();
Intent innerIntent = intent.getParcelableExtra("intent");
innerIntent.setExtrasClassLoader(IPCData.class.getClassLoader());
IPCData data = innerIntent.getParcelableExtra("data");
String key1 = innerIntent.getStringExtra("key1");

网上已有讨论:https://issuetracker.google.com/issues/37053389

上一篇下一篇

猜你喜欢

热点阅读