前言

前面完成了搜索和连接,接下来就是传输数据。


一、获取特征值

因为BLE蓝牙是根据特征值来进行输出读取,所以我们先要获取所有服务和特征值,这里可以通过重写BluetoothGattCallback里面的onServicesDiscovered方法获取

  @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status == bluetoothGatt.GATT_SUCCESS){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //遍历services
                        for(BluetoothGattService service:bluetoothGatt.getServices()){
                            Log.d(TAG, "service"+service.getUuid());
                            //遍历Characteristic
                            for (BluetoothGattCharacteristic charac : service.getCharacteristics()){
                                Log.d(TAG, "charac " + charac.getUuid());
                                //将获取到的characteristic存在列表里面
                                listcharac.add(charac);
                            }
                        }
                    }
                });


            }


        }

二、传输数据

1.往蓝牙传入数据

//这里的bluetoothGatt是连接设备的bluetoothGatt = bluetoothDevice.connectGatt(BleConnect1.this, false, bluetoothGattCallback);
bluetoothGatt.writeCharacteristic(//对应的特征值,在listcharac里面);//根据蓝牙的不同,写入数据的特征值不同,根据自己的需求选择特征值

再传入数据之后,会回调 BluetoothGattCallback的

@Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic charac, int status) {
            super.onCharacteristicWrite(gatt, charac, status);
            //写操作后的回调操作
            if (status==BluetoothGatt.GATT_SUCCESS){
                Log.d("TAG2", "onCharacteristicWrite: 1");
            }else {
                Log.d("TAG2", "onCharacteristicWrite: 2");
            }

        }

2.接收数据

bluetoothGatt.readCharacteristic(//对应的特征值,在listcharac里面);//根据蓝牙的不同,接受数据的特征值不同,根据自己的需求选择特征值

再传入数据之后,会回调 BluetoothGattCallback的

@Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            if (status == bluetoothGatt.GATT_SUCCESS) {
                byte[] data = characteristic.getValue();//获取该特征值中的数据
            }else {
                Log.d("TAG2", "onCharacteristicRead: 失败");
            }

        }

总结

整个BLE的流程就是这样
安卓BLE蓝牙开发总结(一):BLE蓝牙的打开与搜索
安卓BLE蓝牙开发总结(二):BLE蓝牙的连接
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐