(1) 新建一个AIDL文件,文件后缀名为.aidl。
package com.matrix.aidl;
interface StudentQuery {
String query(String no);
}
注意:aidl文件中不能出现public,private等关键字。
(2)新建一个服务类继承Service类。
①这里的StudentQueryBinder 类继承的StudentQuery.Stub接口。
public class RemoteStudentQuery extends Service {
private Map<String, String> studnets = new HashMap<String, String>();
IBinder binder = new StudentQueryBinder();
@Override
public IBinder onBind(Intent intent) {
this.studnets.put("1", "like");
this.studnets.put("2", "chris");
this.studnets.put("3", "sam");
this.studnets.put("4", "jerry");
return binder;
}
public String queryStudent(String no){
return this.studnets.get(no);
}
private final class StudentQueryBinder extends StudentQuery.Stub{
@Override
public String query(String no) throws RemoteException {
return queryStudent(no);
}
}
}
(3) 在AndroidManifest.xml文件中配置service,这里用隐式意图来调用。
<service android:name="com.matrix.service.RemoteStudentQuery">
<intent-filter >
<action android:name="com.matrix.student.query"/>
</intent-filter>
</service>
(4) 在项目B中拷入之前的aidl文件
(5) 开启并调用服务
①studentQuery = StudentQuery.Stub.asInterface(service);通过这个方法将Intent转换成aidl所定义的接口。
②
private final class SearchClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
String no = txtNo.getText().toString();
try {
String name = studentQuery.query(no);
lblName.setText(name);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
private final class StudentConnector implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
studentQuery = StudentQuery.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}