Android手机与多个BLE设备通信

       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类中发现:

    public boolean connect(final String address) { ......
        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
......}
虽然 BluetoothAdapter只能有一个,但BluetoothGatt可以有多个,将其放置与Arraylist容器中,逐一进行连接即可,下面是我的代码:

private ArrayList connectionQueue = new ArrayList();
public boolean connect(final String address) {
        ......
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        BluetoothGatt bluetoothGatt;
        bluetoothGatt = device.connectGatt(this, false, mGattCallback);
        connectionQueue.add(bluetoothGatt);
        .......
    }

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


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


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

你可能感兴趣的:(Android,移动开发,BLE,android,BLE,蓝牙4.0,多设备)