BluetoothDevice.createrfcommsockettoservicerecord 为空

BluetoothDevice.createrfcommsockettoservicerecord is Null

我已成功识别蓝牙设备 (HC-05),我得到了它的名称、MAC 地址和绑定状态,但是当我尝试创建客户端套接字以启动与它的蓝牙连接我得到了一个空套接字。

//initializing bluetooth adapter
    val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
    if (bluetoothAdapter?.isEnabled == false) {
        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
    }

    //creating a list of PAIRED DEVICES
    val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices

    //define a BluetoothDevice (the first on the list)
    pairedDevices?.forEach { device ->
        val deviceName = device.name
        val deviceHardwareAddress = device.address // MAC address
        val arduino: BluetoothDevice = pairedDevices.first()

然后:

val arduinoSocket = arduino?.createRfcommSocketToServiceRecord(uuid)

这是 Null。

我的 UUID 是:

private val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")

有什么见解吗?

您的代码大部分看起来都不错。 您可以尝试使用下面的代码尝试获取设备的实际 uuid,而不是使用默认的 uuid。

BluetoothSocket arduinoSocket = arduino.createRfcommSocketToServiceRecord(arduino.getUuids()[0].getUuid());