我有一个.aidl文件,它定义了一个接口类型的单个parcelable,比如说
parcelable MyInterface;其中MyInterface是在MyInterface.java中声明的java接口,它扩展了Parcelable接口。但是,既然接口类不知道具体的实现,因此无法实现createFromParcel()方法,我该如何为接口执行此操作呢?
android运行时将如何决定调用哪个创建者(从哪个子类)?在.aidl文件中使用接口类型是不可能的吗?
发布于 2014-06-18 18:25:44
在AIDL上实现Parcelable
Parcelable第一步:-创建一个不同的.aidl文件,用于定义类(Parcelable类)。
(Student.aidl)
package com.aidl;
parcelable Student;我们写这篇文章是因为aidl可以检测到学生类。
学生第二步:-现在你必须定义一个名为的java类,并在这个类中实现parcable接口。parcable接口有两个抽象方法,您必须在学生类中实现它们。
import android.os.Parcel;
import android.os.Parcelable;
public class Student implements Parcelable {
public String name;
public String father_name;
public Student(Parcel source)
{
name = source.readString();
father_name = source.readString();
}
public Student()
{}
public void setName(String name)
{
this.name = name;
}
public void setFatherName(String father_name)
{
this.father_name = father_name;
}// parcable接口方法
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(name);
dest.writeString(father_name);
}任何实现的类中的Parcelable都必须提供CREATOR字段。创建者类型必须为Parcelable.Creator。在这里我们写我们的类名代替T,例如。学生。在对象的UnMarshalling过程中使用CREATOR。
它有两个方法--
1-T createFromParcel(Parcel parcel) :This method is called when UnMarshalling happen
during receiving the data. Keep care that we receive the data member in same sequence
as we write in writeToPacel(). Here we create a constructor in which we demarshalling
the data.
2-NewArray(int size) : Here we just create an array of given size and return.
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
@Override
public Student createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new Student(source);
}
@Override
public Student[] newArray(int size) {
// TODO Auto-generated method stub
return new Student[size];
}
};有关更多信息,请访问:Check Here
发布于 2014-06-18 17:49:37
MyInterface;”实际上不会在gen文件夹中生成任何东西,所以使用这种MyInterface类型的任何接口的函数签名都需要它。
发布于 2017-01-15 07:58:01
我遇到了类似的情况,并想分享我的所作所为。我有下面的aidl主接口,里面包含了另一个接口。
//ICounterAidlInterface.aidl
import path.to.aidldirectory.CounterListener
interface ICounterAidlInterface {
int getCounter();
void setCounterListener(CounterListener listener);
}别忘了导入。
问题是如何表示这种新类型:CounterListener。由于CounterListener本身是一个接口,您不需要将其标记为可打包。
您还需要为CounterListener创建另一个aidl文件。因此,我创建了另一个aidl文件:
//CounterListener.aidl
interface CounterListener{
void newData(int data);
}希望这能有所帮助:)
https://stackoverflow.com/questions/7791998
复制相似问题