Android AIDL传递类对象

Android 使用AIDL来进行跨进程通讯时,除了传递基本数据类型之外,还可以传递类对象,值得注意的是该类必须实现Parcelable接口。具体实现方案如下(本文居于已经了解并可以实现使用bindService来进行跨进程通讯)
server端
1,编写需要传递的类对象并实现Parcelable接口


public class Student implements Parcelable {
    private String name;
    private int id;
    protected Student(Parcel in) {
        name = in.readString();
        id = in.readInt();
    }
    public Student() {

    }
    public void setId(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };
    @Override
    public int describeContents() {
        return 0;
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(id);
    }
    public void readFromParcel(Parcel reply) {
        name = reply.readString();
        id = reply.readInt();
    }
}

注意readFromParcel不是由Parcelable 自动生成的,需要我们自己手动写一下,否则后面的编译不通过。

2,编写对应的aidl文件
这个aidl文件的命名需要和上面传递的类对象的命名是一致的,而且包名也要一致。如Student.aidl

// Student.aidl
package com.test.testserver;

// Declare any non-default types here with import statements
parcelable Student;

这个aidl文件里什么都不用写,就只要声明parcelable 即可

3,添加到跨进程通讯需要的aidl文件中,如:

// ITestInterface.aidl
package com.test.testserver;
import com.test.testserver.Student;
// Declare any non-default types here with import statements

interface ITestInterface {
 
    int getStudentInfo(out Student student);

}

注意,必须带有in,out或者inout 修饰,否则编译不通过。
4,实现,供客户端调用

public class TestService extends ITestInterface.Stub{
	//省略
	  @Override
    public int getStudentInfo(Student student) throws RemoteException {
        Log.d(Utils.TAG, "service getStudentInfo: "+student);
        student.setId(10);
        student.setName("test");
        return 0;
    }
}

client端
1,将Student.java,Student.aidl,ITestInterface.aidl文件从server端拷贝过来,注意包名需要和server端保持一致
2,使用

//绑定服务时被调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
	Log.d("test", "onServiceConnected: ");
	binder = ITestInterface.Stub.asInterface(service);
}

//调用
Student student = new Student();
 try {
	binder.getStudentInfo(student);
 	Log.d("test", "client student: "+student);//1
} catch (RemoteException e) {
	e.printStackTrace();
}

注释1处,可以得到server端传递过来的Student对象。

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值