如何使用AIDL
服务端
1.先建立一个android工程,用作服务端
创建一个android工程,用来充当跨进程通信的服务端。
2.创建一个包名用来存放aidl文件
创建一个包名用来存放aidl文件,比如com.xyz.sayhi.aidl,在里面新建IBookManager.aidl文件.
interface IBookManager {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
String getName();
}
- 编写服务端的服务类MyService
public class MyService extends Service {
//实现了AIDL的抽象函数
private IBookManager.Stub mbinder = new IBookManager.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
//什么也com.xyz.sayhi.MyService不做
}
@Override
public String getName() throws RemoteException {
return "这是服务端提供的名字";
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mbinder;
}
@Override
public void onCreate() {
super.onCreate();
}
}
- 配置清单文件
<service
android:name=".MyService"
android:exported="true" >
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="com.xyz.sayhi.MyService" />
</intent-filter>
</service>
客户端
1、将IBookManager.aidl文件放到aidl目录下,并且包名跟com.xyz.sayhi保持一致。
2、绑定服务
Intent intentService = new Intent("com.xyz.sayhi.MyService");
intentService.setPackage("com.xyz.sayhi");
MainActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);
3、获取服务端提供的服务
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
//通过服务端onBind方法返回的binder对象得到IBookManager的实例,得到实例就可以调用它的方法了
mIBookManager = IBookManager.Stub.asInterface(binder);
Toast.makeText(getApplicationContext(), mIBookManager.getName()+"",Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mIBookManager = null;
}
};