Android 蓝牙BLE开发(二 基本流程)

Android 蓝牙BLE开发(二 基本流程)

一、概述

低功耗蓝牙(BLE)实现交互功能可以分为4个步骤:

发现设备--> 配对/绑定设备--> 建立连接--> 数据通信

1、发现设备

    主设备(Central),发现方, BluetoothAdapter.startLeScan();

    从设备(peripheral), 被发现方, 发出广播,以供发现。


2、配对/绑定设备

    配对是建立两者的对应关系,绑定则把这层关系保存固定下来并记进行强化。


3、建立连接

    建立GATT连接: 

    获取相应BLE从设备的BluetoothDevice:  BluetoothAdapter.getRemoteDevice(address); // address 指的是MAC地址

    获取设备连接: BluetoothDevice.connectGatt(this, false, mGattCallback));

    此时的连接,只能进行监听,即获取到当前BLE从设备广播出来的数据。


4、数据通信

    直接获取到从设备的characteristic, 而characteristic是Service下面的一层。

    4.1、 通过BLE设备相应的Service_UUID获取相应的BluetoothGattService:

                BluetoothDevice.connectGatt(this, false, mGattCallback)返回BluetoothGatt对象。

                调用BluetoothGatt.getService(Service_UUID)获取相应的BluetoothGattService。

    4.2、 调用BluetoothGattService和对应的Characteristic的写入UUID获取相应的BluetoothGattCharacteristic。

                BluetoothGattService.getCharacteristic(Characteristic_UUID)获得。

    4.3、 设置需要发送的命令之。

                调用BluetoothGattCharacteristic.setValue(value)进行设置。value一般为byte[]。

    4.4、 使用BluetoothGatt的写入方法,writeCharacteristic(TextChar)完成命令发送。

    4.5、 读数据是则会用到readCharacteristic()。

猜你喜欢

转载自blog.csdn.net/RX_780/article/details/80560423