随着物联网时代的到来,越来越多的智能硬件设备开始流行起来,比如智能手环、心率检测仪、以及各式各样的智能家具和玩具类产品。安卓4.3(API 18)为BLE的核心功能提供平台支持和API,App可以利用它来发现设备、查询服务和读写特性。相比传统的蓝牙,BLE更显著的特点是低功耗。本文主要讲解Android低功耗蓝牙的api使用以及蓝牙扫描、连接、发送数据、接收数据等一系列操作,并主要介绍本人封装的BleLib蓝牙库,非常适合蓝牙初学者使用,只需要一行代码注入就OK了,而且用法也极其简单,下面会专门讲解BleLib库的使用。
目录
废话不说,先来看下Demo中的效果图:
一、原生API的详细讲解
在BLE协议中,有两个角色,周边(Periphery)和中央(Central);周边是数据提供者,中央是数据使用/处理者,一个中央可以同时连接多个周边,但是一个周边某一时刻只能连接一个中央。
首先使用蓝牙就不得不说BluetoothGatt和BluetoothGattCallback这两个类,该类继承自BluetoothProfile,BluetoothGatt作为中央来使用和处理数据,通过BluetoothGatt可以连接设备(connect),发现服务(discoverServices),并把相应地属性返回到BluetoothGattCallback,BluetoothGattCallback返回中央的状态和周边提供的数据。
1. 蓝牙开发流程:
我们蓝牙操作的主要目的就是为了拿到中央BluetoothGatt这个对象,进而进行接下来的所有一系列操作,如下:
1.BluetoothManager bluetoothManager
= (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
2.BluetoothAdapt btAdapter = bluetoothManager.getAdapter();
3.btAdapter.startLeScan( BluetoothAdapter.LeScanCallback);
4.从LeScanCallback中得到BluetoothDevice
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {…..}
5.用BluetoothDevice得到BluetoothGatt: gatt = device.connectGatt(this, true, gattCallback);
这时总算拿到中央BluetoothGatt了,它有很多的方法,调用这些方法,你就可以通过BluetoothGattCallback和周边BluetoothGattServer交互了。
2. 主要类的大致理解:
-
BluetoothProfile: 一个通用的规范,按照这个规范来收发数据。
-
BluetoothManager:通过BluetoothManager来获取BluetoothAdapter
如:BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
-
BluetoothAdapter:一个Android系统只有一个BluetoothAdapter ,通过BluetoothManager 获取
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
-
BluetoothGattDescriptor:可以看成是描述符,对Characteristic的描述,包括范围、计量单位等。
-
BluetoothGattService:服务,Characteristic的集合。
-
BluetoothGattCallback:已经连接上设备,对设备的某些操作后返回的结果。这里必须提醒下,已经连接上设备后的才可以返回,没有返回的认真看看有没有连接上设备。
private BluetoothGattCallback GattCallback = new BluetoothGattCallback() { // 这里有9个要实现的方法,看情况要实现那些,用到那些就实现那些 public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){}; public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){ }; }; BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); BluetoothGatt gatt = device.connectGatt(this, false, mGattCallback);