AIDL ERROR while trying to return custom class obj

2019-08-14 18:11发布

问题:

I am trying to pass 'Response' class object using IPC in AIDL. I have made the class parcelable:

public class Response implements Parcelable{
    private long id;
    private String speechString;
    private List<String> responseString = new ArrayList<String>();


    //set
    ...
    }

    //get
    ...

    public Response(Parcel in) {
        id = in.readLong();
        speechString = in.readString();
        if (in.readByte() == 0x01) {
            responseString = new ArrayList<String>();
            in.readList(responseString, String.class.getClassLoader());
        } else {
            responseString = null;
        }
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeString(speechString);
        if (responseString == null) {
            dest.writeByte((byte) (0x00));
        } else {
            dest.writeByte((byte) (0x01));
            dest.writeList(responseString);
        }
    }

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public Response createFromParcel(Parcel in) {
            return new Response(in);
        }

        public Response[] newArray(int size) {
            return new Response[size];
        }
    };
}

Defined Response.aidl:

package com.example;

parcelable Response;

IappMain.aidl is used for IPC and is defined as following:

package com.example;

// Declare any non-default types here with import statements
import com.example.Response;

interface IOizuuMain {
    int app(String aString);

    Response getResponseByString(String string);
}

but upon building the project, it gives me the following error in IappMain.java: "error: incompatible types: Object cannot be converted to Response" at this line:

_result = com.example.Response.CREATOR.createFromParcel(_reply);

回答1:

The error is being caused by this line:

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {

Type parameters need to be added to both the return type and the object being created. The change to add type parameters is this:

public static final Parcelable.Creator<Response> CREATOR =
    new Parcelable.Creator<Response>() {


回答2:

try to add public Response() {}

above to the below mentioned code.

 public Response(Parcel in) { .....

.... }

so it should look like

public Response(){}

public Response(Parcel in) { ..... .... }