Android手机与多个BLE设备通信

文章转载来自于:http://blog.csdn.net/mark_sssss/article/details/45063813

 

BLE是蓝牙4.0的核心Profile,主打功能是快速搜索,快速连接,超低功耗保持连接和传输数据,弱点是数据传输速率低,由于BLE的低功耗特点,因此普遍用于穿戴设备。Android 4.3才开始支持BLE API。

 

       本文改自Android Sample: BluetoothLeGatt(可参见http://developer.android.com/samples/BluetoothLeGatt/index.html,如果不能翻墙,sdk本地帮助文档中也有)。

 

       以上的例子是一对一的,也就是一次性只能连接一个设备,但很多情况下需要同时连接多个设备,收取多个设备的数据,那就很麻烦了,因为网上的相关资料很少,stackoverflow上有相关的帖子,全英文,而且也不全。

 

       原本我的想法是,既然sample中一个service连接一个设备,那我开多个service不就可以连接多个设备了?但事实并非这么简单,因为一个Android系统只能有一个BluetoothAdapter,那怎么实现开多个service呢?我一时也没能实现。

 

       后来我翻看了Sample的源码,在BluetoothLeService类中发现:

 

 
  1. public boolean connect(final String address) { ......

  2. final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

  3. if (device == null) {

  4. Log.w(TAG, "Device not found. Unable to connect.");

  5. return false;

  6. }

  7. mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

  8. ......}

 

虽然BluetoothAdapter只能有一个,但BluetoothGatt可以有多个,将其放置与Arraylist容器中,逐一进行连接即可,下面是我的代码:

 
  1. private ArrayList<BluetoothGatt> connectionQueue = new ArrayList<BluetoothGatt>();

  2.  
  3. public boolean connect(final String address) {

  4. ......

  5. BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

  6. if (device == null) {

  7. Log.w(TAG, "Device not found. Unable to connect.");

  8. return false;

  9. }

  10. BluetoothGatt bluetoothGatt;

  11. bluetoothGatt = device.connectGatt(this, false, mGattCallback);

  12. connectionQueue.add(bluetoothGatt);

  13. .......

  14. }

 

 

 
 

       接下来就是在disconnect(),close()等方法中增加对connectionQueue的操作即可。

 

       我的Demo源码在http://download.csdn.net/detail/mark_sssss/8598191

 

       不过由于我的项目需要,这个Demo只能接收字符数据,而不能发送数据。如果添加发数据的功能,你可以参考这篇文章http://blog.csdn.net/hellogv/article/details/24267685,按以上方法,将对BluetoothGatt的操作以connectionQueue的方式实现即可。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值