安卓BLE蓝牙开发总结(三):接受和传输数据


前言

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


一、获取特征值

因为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蓝牙的连接
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小周bb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值