分享

7. 使用AIDL调用远程服务

 黎可图书馆 2013-09-20
一. 定义
AIDL是一种借口定义语言,用于约束两个进程之间的通讯规则,供编译器生成代码,实现Android设备上的两个进程间通信。

二. 实现
(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) {
}
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多