Aidl机制提供进程间传递对象。
当然在进程间传递对象也可以使用广播吧,但他们的使用方向是不一样的,大概如此。

实现Android进程间传递对象的步骤如下:
1.编写aidl接口。
TestService.aidl
package com.xwangly.service;interface TestService {/** * 获取人员列表 * @param sex * @return */List getPersonList(in String sex);/** * 查询人员姓名 * @param id * @return */String getPersonName(int id);/** * 查询人员ID * @param name * @return */int getPersonId(in String name);/** * 显示人员信息 * @param name */void showPersonInfo(out List personList);}

aidl中的参数有in或out。当然out也可以使用返回值的形式,如getPersonName函数。

2.编写远程服务。远程服务类就是普通的Android服务。不过该服务的onBind方法要返回一个TestService.Stub对象。一般在该服务中需要实现该类并创建对象。
com.xwangly.service.RemoteService.java
package com.xwangly.service;import java.util.ArrayList;import java.util.List;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.RemoteException;import android.util.Log;public class RemoteService extends Service {private final String TAG = "RemoteService";public TestService.Stub aidl = new TestService.Stub(){public int getPersonId(String name) throws RemoteException {// TODO Auto-generated method stubreturn name=="wang"?1:2;}public String getPersonName(int id) throws RemoteException {// TODO Auto-generated method stubreturn "wang "+id;}public void showPersonInfo(List personList) throws RemoteException {// TODO Auto-generated method stubpersonList.add("wang");personList.add("xiao");}public List getPersonList(String sex)throws RemoteException {// TODO Auto-generated method stub//personList = new ArrayList();List personList = new ArrayList();personList.add("wang "+sex);return personList;}};@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubLog.i(TAG, intent.getAction());return aidl;}}

在manifest中配置如下:
    <service android:name="RemoteService">    <intent-filter>    <action android:name="com.xwangly.service.TestService" />    </intent-filter></service>


3.客户端连接远程服务,得到aidl接口的一个实例,通过该实例,客户端可以像本地服务一样使用该服务。(客户端即为另一应用。)
首先客户端需要实现一个服务连接器serviceConnection,在该接口的onServiceConnected中实现创建服务接口,代码如下:
tService = TestService.Stub.asInterface(service);

然后客户端需要bindService
Intent intent = new Intent("com.xwangly.service.TestService");bindService(intent, connect, BIND_AUTO_CREATE);

Intent的action即为服务端aidl文件的类全名。需要在服务端的manifest中配置相应的action过滤。如第二步中的manifest配置所示。
connect即为刚实现的serviceConnection实例。
这样客户端就可以使用tService对象了。

更多相关文章

  1. 类和 Json对象
  2. 浅析android通过jni控制service服务程序的简易流程
  3. Android(安卓)Service AIDL
  4. haproxy根据客户端浏览器进行跳转
  5. Android中文API(144) —— JsonWriter
  6. Android之Handler用法总结
  7. Android架构分析之使用自定义硬件抽象层(HAL)模块
  8. android通过ksoap2对webservice的解析
  9. Android(安卓)View的介绍和使用

随机推荐

  1. Android中为每个Activity显示自己的标题
  2. 【转】【Android游戏开发十五】关于Andro
  3. Android(安卓)关于Intent的一些简略总结
  4. Android(安卓)判断sd卡和sim卡是否可用
  5. 解决打开Android(安卓)Device Monitor一
  6. Android(安卓)Camera Framework Stream(
  7. RIL flow
  8. android 上的一个网络接口和图片框架
  9. android hasSystemFeature函数及系统特性
  10. Android(安卓)Internet应用实现获取天气