且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android Studio Ble Gatt 连接将数据写入自定义服务特性

更新时间:2023-01-24 07:47:57

我通过在 Bluetoothle 服务内部创建一个函数解决了我的问题.这是蓝牙 gatt 连接所在的位置.功能就是这样.

I fixed my issue by creating a function inside of the Bluetoothle service. This is where the bluetooth gatt connection is. The function is like so.

public void writeCharacteristic(int Data) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }

    byte[] value = intToByteArray(Data);

    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("f3641400-00b0-4240-ba50-05ca45bf8abc"));
    if(mCustomService == null){
        Log.w(TAG, "Custom BLE Service not found");
        return;
    }
    /*get the read characteristic from the service*/
    BluetoothGattCharacteristic characteristic = mCustomService.getCharacteristic(UUID.fromString("f3641401-00b0-4240-ba50-05ca45bf8abc"));
    characteristic.setValue(value);
    mBluetoothGatt.writeCharacteristic(characteristic);
}

它只需要一个数据(传入它的 Int 值).然后这个被我的蓝牙板接收,可以在终端上看到它的数据被正确发送.

It just needs a data (Int value passing into it). Then this is received by my Bluetooth board and, can see its data on a terminal being sent correctly.