这是第六篇文章主要讲的是BoundService中用AIDL实现IPC,自定义属性的使用,上篇博客已经说明了AIDL应该如何使用,但是如果想传入一个自定义的类的时候怎么办呢?那么这篇博客将对这种情况进行详细描述
废话不多说了,直接上步骤,前期的步骤上篇博客已经说明了,这篇是对上篇博客的扩展
1.新建一AIDL文件,并与你即将定义的类型名字相同,例如Person.aidl
2.新建一个类Person.java,并将实现类的get,set方法
3.实现Parcelable类和其方法
(1)writeToParcel()方法中写入属性
@Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(name); parcel.writeString(work); }
(2)创建一个构造器,结构如下
public static final Parcelable.Creator<Person>CREATOR = new Parcelable.Creator<Person>(){ public Person createFromParcel(Parcel in){ Person p = new Person(); p.name = in.readString(); p.work = in.readString(); return p; } @Override public Person[] newArray(int i) { return new Person[i]; } };
构造器的格式基本是这样的可以直接复制这段代码进行更改
Person类的全部代码在这里哦~
public class Person implements Parcelable { private String name; private String work; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWork() { return work; } public void setWork(String work) { this.work = work; } @Override public int describeContents() { return 0; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", work='" + work + '\'' + '}'; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(name); parcel.writeString(work); } public static final Parcelable.Creator<Person>CREATOR = new Parcelable.Creator<Person>(){ public Person createFromParcel(Parcel in){ Person p = new Person(); p.name = in.readString(); p.work = in.readString(); return p; } @Override public Person[] newArray(int i) { return new Person[i]; } }; }
4.重写AIDL文件
// Person.aidl package com.lw.myboundservice_ipc; parcelable Person;
5.在上一个aidl文件种导包
// MyAidl.aidl package com.lw.myboundservice_ipc; import com.lw.myboundservice_ipc.Person; // Declare any non-default types here with import statements interface MyAidl { /**
6.然后跟传递普通变量一样尽情的使用吧
(1)在MyAidl文件中添加Person返回类型的函数
interface MyAidl { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void setString(String str); String desc(); Person getPerson(); void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); }
(2)在Mainactivity调用就好
public void callClick(View view){ if(myAidl!=null){ try { myAidl.setString("测试传递数据"); Log.e("ceshi","是传递成功---"+myAidl.desc()); Log.e("ceshi","自定义类型的数据获取---"+myAidl.getPerson()); } catch (RemoteException e) { e.printStackTrace(); } } }
附上渣渣源码:源码
Android Service详解系列
————————————————
原文链接:https://blog.csdn.net/superbiglw/article/details/53156431