server端的实现
1.创建 aidl文件 (例如ICatl.aidl)
2。创建一个server 并在server中创建一个内部类,继承aidl文件的stub例如:
public class AidlService extends Service {
private CatBinder catBinder;
//此处要继承Stub,实现ICat和IBinder接口
public class CatBinder extends ICat.Stub
{
@Override
public String getColor() throws RemoteException {
//这里做一些操作,获得客户端想要的数据,例如查询数据库
return "red";
}
@Override
public double getWeight() throws RemoteException {
return 9.9;
}
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"oncreat",Toast.LENGTH_SHORT).show();
catBinder = new CatBinder();
}
@Override
public IBinder onBind(Intent intent) {
return catBinder;
}
@Override
public void onDestroy() {
System.out.println("remote service destroy");
}
}
注意:
如果是eclipse需要在src目录和ICat.aidl相同的包名下创建 Icat.java文件
如果是android studio编译器不用创建 ICat.java 编译器会自动创建
注意使用aidl的server 一定要和aidl文件有相同的包名
client端的实现
1.将服务类的aidl文件拷贝过来 (注意:和service端的aidl一定在一个包名下面)
2.需要从服务端获得数据时,绑定服务
Intent intent = new Intent();
intent.setAction("AidlService");
intent.setPackage(包名);
bindService(intent,conn, Service.BIND_AUTO_CREATE)
bind服务成功后回调ServiceConnection的onServiceConnected方法,
ServiceConnection conn =new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(MainActivity.this,"connected",Toast.LENGTH_SHORT).show();
mICat = ICat.Stub.asInterface(service);
try {
String color = mICat.getColor();
} catch (RemoteException e) {
e.printStackTrace();
}
}