四、远程服务
- 远程服务一般用于进程间通信。
- aidl是android接口定义语言,用于创建远程调用的服务接口
/**
* 远程服务:
* 1.编写aidl文件,自动生成抽象接口服务(android接口定义语言),文件名和接口名(IRemoteService)一致
* 2.创建一个服务(RemoteService)继承Service,里面有一个该接口(IRemoteService)内部类Stub类型变量,实现具体的方法
* 3.在Manifest中注册该实现的服务(RemoteService),并填写action(xxx.action.RemoteService)
* 4.将IRemoteService文件导出为jar文件,导入需要的工程中。
* 5.绑定服务时需要填入action(xxx.action.RemoteService)
* 6.在ServiceConnection中onServiceConnected方法中通过
* IRemoteService.Stub的asInterface(service)得到IRemoteService接口
* 7.调用IRemoteService的相关方法即可
*
*/
aidl文件(CalcService.aidl)
注意:文件名和接口名一致
package com.hasen.aidltest ;
interface CalcService{
float add(float a,float b) ;
}
将自动在gen目录中生成CalcService.java文件
在src中创建服务,其中的Stub对象是接口中的内部类CalcService.Stub
public class RemoteService extends Service {
@Override
public IBinder onBind(Intent intent) {
return calcBinder;
}
private Stub calcBinder = new com.hasen.aidltest.CalcService.Stub() {
@Override
public float add(float a, float b) throws RemoteException {
return a+b;
}
};
}
配置manifest.xml
<service android:name=".RemoteService">
<intent-filter >
<action android:name="com.hasen.aidltest.action.RemoteService"/>
</intent-filter>
</service>
将生成的CalcService.java文件导出为jar文件(export-->java-->jar doc)
客户端:(新的项目文件)
绑定服务
remoteService = new Intent("com.hasen.aidltest.action.RemoteService");
this.bindService(remoteService, remoteConn, BIND_AUTO_CREATE);
private ServiceConnection remoteConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//通过远程服务接口的内部类Stub调用asInterface得到该接口
CalcService cs =com.hasen.aidltest.CalcService.Stub.asInterface(service) ;
try {
float f =cs.add(23, (float)(8*Math.random())) ;
Toast.makeText(ClscActivity.this, f+"", Toast.LENGTH_SHORT).show() ;
} catch (RemoteException e) {
e.printStackTrace();
}
unbindService(remoteConn);
}
} ;