package com.ch.android.demo4;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.UserHandle;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zgq on 2019/6/19 16:17
*/
public class PersonService extends Service {
@Override
public IBinder onBind(Intent intent) {
return new PersonStub();
}
public synchronized ComponentName startForegroundServiceAsUser(Intent service, UserHandle user) {
return null;
}
private static final class PersonStub extends PersonController.Stub {
@Override
public List<Person> getPersonList() throws RemoteException {
//测试数据
List<Person> list = new ArrayList<>();
Person person = new Person("zgq");
list.add(person);
return list;
}
}
}
//服务端使用到的实体类
package com.ch.android.demo4;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by zgq on 2019/6/19 16:11
*/
public class Person implements Parcelable {
private String name;
public Person(String name) {
this.name = name;
}
protected Person(Parcel in) {
name = in.readString();
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
}
}
1.什么是AIDL?作用?
AIDL是Android Interface Definition Language的缩写,表示安卓接口定义语言;其主要作用就是跨进程间的一种通信机制。
2.如何定义AIDL
2.1 定义AIDL文件
//创建接口文件:PersonController.aidl
//接口使用到的实体类文件:Person.aidl
2.2 定义服务端
定义完AIDL文件之后,手动编译项目;然后创建服务端Service。代码如下: //服务端Service
//服务端使用到的实体类
//清单文件中注册
AIDL接口中小知识点:
inout类型参数:数据双向流动。
2.4 客户端调用
如果服务端和客户端不在同一个工程,首先需要将aidl文件拷贝到客户端应用中。具体使用过程如下:
3.AIDL内部怎么实现进程通信的?
AIDL的内部通信机制使用的是Binder机制,会在后面的专题单独总结。
4.小结
AIDL是Android中进行跨进程通信的一种机制。提供的统一的编程方式来定义接口。