上一篇文章中说到了关于蓝牙连接的一些问题,今天主要给大家介绍一下,关于BluetoothGattCallback中的一些常用到的回调方法。其实还是强烈建议大家看一看BluetoothGattCallback的源码,它里面会有更详细的介绍;这里我还是不建议初学者去直接使用一些三方库,因为首先自己要对一些原理性的东西有了一定的了解之后,再去尝试使用框架,才能去发现三方框架的一些优点,这里说一下我以前遇到过得一个坑,曾经使用过fastble这个库,虽然在初始化设置等方面可以省去我们不少时间,但是当你连接设备成功之后,调用发现服务,你会发现onServicesDiscovered方法不会回调。这个时候你就会发现从最原始的方法一点点写起,才是对自己的开发最有益处的。接下来步入正题:
首先,我们需要定义几个蓝牙的特征值:
private String SERVICES_UUID = "0000ff00-0000-1000-8000-00805f9b34fb"; //服务UUID private String WRITE_UUID = "0000ff02-0000-1000-8000-00805f9b34fb"; //写入特征UUID private String NOTIFY_UUID = "0000ff01-0000-1000-8000-00805f9b34fb"; //监听通知特征的UUID
接下来说一下如何在BluetoothGattCallback中写入这些特征值:
//下面列举几个常用的回调方法 BluetoothGattCallback gattCallback = new BluetoothGattCallback() { //连接状态变化时回调 @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { super.onConnectionStateChange(gatt, status, newState); if(newState == BluetoothProfile.STATE_CONNECTED){ // 连接成功状态 //连接成功之后的操作 gatt.discoverServices();// 发现蓝牙服务 }else if(newState == BluetoothProfile.STATE_DISCONNECTED){ // 断开连接状态 //断开连接之后的操作 } } //发现蓝牙服务,在蓝牙连接的时候会调用 @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); if (status == BluetoothGatt.GATT_SUCCESS) { // 发现蓝牙服务成功 List<BluetoothGattService> gattServicesList = gatt.getServices(); for (int i = 0; i < gattServicesList.size(); i++) { Log.d("onServicesDiscovered", "gattServicesList UUID=" + gattServicesList.get(i).getUuid()); if(gattServicesList.get(i).getUuid().equals(UUID.fromString(SERVICES_UUID))){ //如果servicesUUID相同,则做如下处理 //设置写入特征UUID BluetoothGattCharacteristic writeCharacteristic = gattServicesList.get(i).getCharacteristic(UUID.fromString(WRITE_UUID)); //设置监听特征UUID BluetoothGattCharacteristic notifyCharacteristic = gattServicesList.get(i).getCharacteristic(UUID.fromString(NOTIFY_UUID)); //开启监听 gatt.setCharacteristicNotification(notifyCharacteristic,true); break; } } } else { Log.e("onServicesDiscovered", "当前状态:" + status); } } // 当接收到数据时 @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicRead(gatt, characteristic, status); if (status == BluetoothGatt.GATT_SUCCESS) { // 接收数据成功时 } } //当开始写入数据时 @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); if (status == BluetoothGatt.GATT_SUCCESS) { // 写入数据成功时 } } //当特征值发生变化时 @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { super.onCharacteristicChanged(gatt, characteristic); } //当传输最大数据包大小发生变化时 @Override public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { super.onMtuChanged(gatt, mtu, status); if (status == BluetoothGatt.GATT_SUCCESS) { // 修改最大传输数据包值成功 } } };
关于BluetoothGattCallback暂时就说这么多了,如有说的不当之处,也欢迎大家指正,互相交流,共同进步。谢谢~