BLE连接建立失败可能由以下几种原因引起:
示例代码:
// 设置蓝牙连接参数 BluetoothGatt bluetoothGatt = device.connectGatt(this, false, bluetoothGattCallback); BluetoothGattCharacteristic characteristic = bluetoothGatt.getService(serviceUUID) .getCharacteristic(characteristicUUID); characteristic.setValue(value); characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE; bluetoothGatt.writeCharacteristic(characteristic); // 发送蓝牙数据
// 实现蓝牙连接回调函数 private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { Log.d(TAG, "Connected to GATT server."); gatt.discoverServices(); // 发现设备服务 } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { Log.d(TAG, "Disconnected from GATT server."); } }
// 其他回调函数
};