通过BluetoothA2DPService学习AIDL心得

本文想结合BluetoothA2DPService讲述一下实现AIDL功能的方法,说的不对的地方,欢迎批评指正:)
1.BluetoothA2DPService的实现:
 1)首先在SystemService代码中我们看到
    bluetoothA2dp = new BluetoothA2dpService(context);
        ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE, bluetoothA2dp);
      这样bluetoothA2dp这个实例就交给ServiceManager去管理了。
 2)BluetoothA2DP类只是实现了BluetoothA2DPService的代理,并对其进行了一些扩展,但仍然通过下列代码来获取Service实例来操纵Service的各种功能:
  IBinder b = ServiceManager.getService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE);
  if (b == null) {
      throw new RuntimeException("Bluetooth A2DP service not available!");
  }
  mService = IBluetoothA2dp.Stub.asInterface(b);
 3)此时Client端要实现远程调用只能先创建BluetoothA2DP,当然也可以通过ApplicationContext的getSystemService方法获取,但是目前的代码中没有实现,只能自己添加代码了;)

2.通过上篇文章和A2DP部分代码的学习,可以得出要实现AIDL功能的工作如下:
    1)Service端:
     a)编写AIDL文件XXX.aidl,定义你要使用到的接口
     b)使用makefile或者eclipse的ADT插件生成与之同名的JAVA文件XXX.java
     c)声明一个类继承XXX.Stub,实现定义的接口功能
     d)一般来说,为了方便Client端使用,会写一个类继承Service,然后将实现Stub的类放在Service类的内部
    2)Client端:
     a)如果Service端是一个Android Service(extents Service),则要通过bindService和unbindService来和Service端建立连接或断开连接,同时要声明一个ServiceConnection类(bindService的时候用到),这样连接成功的时候会在onServiceConnected(ComponentName name, IBinder service)中返回一个IBinder,然后调用XXX.Stub.asInterface(IBinder service)返回一个Service的实例,就可以通过该实例调用所有实现的接口了;
     b)如果Service端不是一个Andoird Service实例,Client端可以通过ServiceManager的getService函数获取IBinder,同样调用XXX.Stub.asInterface(IBinder service)返回一个Service的实例。但是这种方式的前提是必须在该Service生成的时候通过ServiceManager的addService方法添加进去让它去管理并赋予一个名称,这样获取的时候直接指定名称调用getService方法就可以得到你想要的Service了。比如IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE)。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值