尝试返回自定义类对象

时间:2015-06-07 13:18:05

标签: java android service android-studio aidl

我正在尝试使用AIDL中的IPC传递'Response'类对象。我让这个班级成为可以的:

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];
        }
    };
}

定义Response.aidl:

package com.example;

parcelable Response;

IappMain.aidl用于IPC,定义如下:

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);
}

但是在构建项目时,它在IappMain.java中给出了以下错误: “错误:不兼容的类型:对象无法转换为响应”在此行:

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

2 个答案:

答案 0 :(得分:2)

错误是由这一行引起的:

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

需要将类型参数添加到返回类型和正在创建的对象中。添加类型参数的更改如下:

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

答案 1 :(得分:0)

尝试添加 公众回应() {}

以上提到的代码。

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

.... }

所以看起来应该是

public Response(){}

公众回应(包裹){..... .... }