#BLE蓝牙开发思路
BLE(即低功耗蓝牙)使用的是GATT协议,协议主要是由特征值characterister提供数据传输的。GATT由很多服务service组成,每个service又包含多个特征值characteristic,比如你读取手环中的心率就是从特定服务service中的特定characteristic中读取的,相应的向手环发送信息也是在相应的特征值中写入数据。所以只要能获取到各个数据类型的characteristic的唯一UUID,就可以获取到外围设备的各类数据。
接下来基于android5.0系统进行开发流程的介绍:
下面基于5.0系统的API开发
1.声明需要的权限
<uses-permission android:name="android.permission.BLUETOOTH"/> 使用蓝牙所需要的权限
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 使用扫描和设置蓝牙的权限(申明这一个权限必须申明上面一个权限)
<uses-featurandroid:name="android.hardware.location.gps/> 5.0以后系统使用蓝牙必须开启GPS定位权限
2. 初始化蓝牙设备
2.1 获取BluetoothAdapter
private BluetoothAdapter mBluetoothAdapter;
final BluetoothManager bluetoothManager = (BluetoothManager); getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
2.2 开启蓝牙
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
3. 扫描蓝牙设备
final BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback() {
@Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
bluetoothDeviceArrayList.add(device);
Log.d(TAG, "run: scanning...");
}
};
mBluetoothAdapter.startLeScan(callback);//开启蓝牙代码
开启蓝牙,扫描到设备后会返回设备的BluetoothDevice,在扫描之后的回调函数中要进行处理。
停止扫描:
void stopLeScan(BluetoothAdapter.LeScanCallback callback)
传入的回调必须是开启蓝牙扫描时传入的回调。
4. 连接蓝牙设备
4.1 首先获取BluetoothDevice
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
通过BluetoothDevice类的ConnectGatt连接
mBluetoothGatt = device.connectGatt(this, false, Callback);#mBluetoothGatt为BluetoothGatt类型
然后:
mBluetoothGatt.connect();
蓝牙会异步执行蓝牙连接的操作,连接成功回调BluetoothGattCalback类的onConnectionStateChange方法。
5.发现设备
蓝牙设备后
BluetoothGatt#discoverService方法,系统异步执行发现服务的过程。
6.读取与写入数据
发现服务后BluetoothGatt#getService获取BluetoothGattService,
再BluetoothGattService#getCharactristic得到BluetoothGattCharactristic.
6.1 读取数据
BluetoothGattCharactristic#readCharacteristic读取特定的数据。
系统读取数据后回调,在BluetoothGattCallback#onCharacteristicRead()方法中调用BluetoothGattCharacteristic#getValue方法读取数据。
6.2 写入数据
BluetoothGattCharactristic#setValue传入写入的数据。
BluetoothGattCharactristic#writeCharacteristic方法异步往设备写入数据
在回调函数BluetoothGattCallback#onCharacteristicWrite中可以执行getValue检查写入的数据
6.3 注册监听实现实时读取蓝牙设备的数据
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
7 断开连接
BluetoothGatt#disconnect断开正在连接的设备
BluetoothGatt#close方法释放资源