【整理】使用AIDL跨进程传递复杂对象的实践例子
首先定义对象类,并实现Parcelable接口,实现接口内的几个方法,看代码,Person.java
package com.example.u3.aidltest; import android.os.Parcel; import android.os.Parcelable; /** * Created by U3 on 2015/3/11. */ public class Person implements Parcelable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } private String pass; @Override public int describeContents() { return 0; } public static final CreatorCREATOR = new Creator () { @Override public Person createFromParcel(Parcel source) { return new Person(source); } @Override public Person[] newArray(int size) { return new Person[size]; } };//用于创建 public Person()//测试用 { name = "hel"; pass = "213"; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeString(pass); } private Person(Parcel in)//必须与上面的写入顺序相同,否则值会错误 { name = in.readString(); pass = in.readString(); } }
然后,新建两个AIDL文件,一个声明接口一个声明上面的类,声明类的AIDL名字必须与类相同,看代码
Person.aidl
package com.example.u3.aidltest;//包名 parcelable Person;
myaidl.aidl
// myaidl.aidl package com.example.u3.aidltest; // Declare any non-default types here with import statements import com.example.u3.aidltest.Person;//需要先引入 interface myaidl { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ Person getperson(in Person s); }
然后在服务中使用自动生成的类,实现方法,见代码
package com.example.u3.aidltest; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * Created by U3 on 2015/3/11. */ public class Server extends Service { class My extends myaidl.Stub {//继承自动生成的类,实现方法 @Override public Person getperson(Person s) throws RemoteException { Log.v("sk", s.getName()+" "+s.getPass()); s.setName("hi!!!!"); return s; } } @Override public IBinder onBind(Intent intent) { return new My(); } }
然后在客户端,复制AIDL文件所在包和Person以及他的包
两边的结构图如下