aidl : android interface defination language 安卓接口定义语言.
提供两个应用程序之间交互的接口
IPC: inter process communication 进程间通讯
首先创建一个远程服务的程序,创建一个Service,在程序中配置它的action,然后创建aidl接口
Service代码:
public class RemoteSerivce extends Service {
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
private class MyBinder extends IService.Stub {
@Override
public void callInServiceMethod() throws RemoteException {
serviceMethod();
}
}
private void serviceMethod() {
System.out.println("远程服务里面的方法");
}
}
配置文件的代码:
<service android:name="com.alan.remodeservice.RemoteSerivce" >
<intent-filter>
<action android:name="aaa.bbb.ccc.remote" />
</intent-filter>
</service>
接着创建一个调用远程服务的方法的程序:
activity代码:
public class MainActivity extends Activity {
private Button mRemoteButton;
private Button mRemoteMethod;
private IService iService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRemoteButton = (Button) findViewById(R.id.button1);
mRemoteMethod = (Button) findViewById(R.id.button2);
// 绑定远程服务
mRemoteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
// 远程配置的action是什么要与之对应
intent.setAction("aaa.bbb.ccc.remote");
bindService(intent, new ServiceConnections(), BIND_AUTO_CREATE);
}
});
// 调用远程服务的方法
mRemoteMethod.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
iService.callInServiceMethod();
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
class ServiceConnections implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 这行是重点
iService = IService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
在这里最重要的是IService.aidl文件,在远程当中的IService.aidl文件的包名与调用远程方法的程序的包名必须要一致,两个程序都必须要有IService.aidl这个文件
IService.aidl代码:
package com.alan.remodeservice;
interface IService {
void callInServiceMethod();
}
这里提醒一下,接口和方法都不能声明为public的,会报错。因为这里的接口默认都是全局可见的。