直接进入正题。
aidl的实质其实是app的server为app的client访问server服务提供的通行证。
aidl的实现主要分为两部分,server和client。
1. 其中server主要要做:
(1)定义aile的接口。
package com.aidl;
interface TestAidlService{
String getName();
}
(2)实现service,并在onBind中返回binder。
实现如下:
public class ServiceImpl extends Service{
private class AidleServiceImpl extends TestAidlService.Stub{
@Override
public String getName() throws RemoteException {
// TODO Auto-generated method stub
System.out.println("sss");
return "wsh";
}
}
AidleServiceImpl binder=new AidleServiceImpl();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
System.out.println("create");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("create");
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
}
(3)再配置文件之中添加service,并添加intentfiliter ,使client能通过intentfiler的过滤访问到该service。
<service
android:name="com.aidl.ServiceImpl">
<intent-filter>
<action android:name="com.aidl.wsh"/>
</intent-filter>
</service>
(4)开启service服务,使client能够获取该服务。
startService(new Intent("com.aidl.wsh"));
2.client 需要做
(1)得到server提供的aidl文件,作为获取server提供服务的通行证。
(2)利用ServiceConnection建立于service的连接。
public class MainActivity extends Activity {
private Button button;
private TestAidlService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(onClickListener);
bindService(new Intent("com.aidl.wsh"), connection, Context.BIND_AUTO_CREATE);
}
private OnClickListener onClickListener=new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
String string=service.getName();
System.out.println(string+"client");
System.out.println( service.getName());
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
service=TestAidlService.Stub.asInterface(arg1);
System.out.println("Bind Success:"+service);
}
};
}
ps:其中有几个地方需要注意
(1)server和client工程中的包含aidl文件的包名要完全相同。
(2)再配置文件之中添加 <intent-filter>的时候,action的命名是随意的,但是client绑定该service时候,intent的过滤器应该和service中配置文件的过滤器一样。
(3)最后附上简单的源码:点击打开链接