美文网首页
Intent的extra里又放了自定义Parcelable的in

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

作者: 我想04 | 来源:发表于2019-12-26 11:24 被阅读0次

    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

    相关文章

      网友评论

          本文标题:Intent的extra里又放了自定义Parcelable的in

          本文链接:https://www.haomeiwen.com/subject/epnructx.html