0

我需要连接到充当服务器的蓝牙设备。我知道它的 UUID(至少设备的文档包含它)。但是,当我尝试连接它时出现异常。发现部分成功发生。

在下文中,我引用了相关的代码部分。

这是发现。成功找到我的设备后,我尝试连接到它。

private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
private val bluetoothReceiver = object : BroadcastReceiver() {
  override fun onReceive(context: Context, intent: Intent) {
    val action: String = intent.action
    when (action) {
      BluetoothDevice.ACTION_FOUND -> {
        val foundDevice: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
        Log.i("NAME", foundDevice.name)
        if (foundDevice.name.startsWith("RN487")) {
          bluetoothAdapter?.cancelDiscovery()
          device = foundDevice
          val connectThread = ConnectThread(device)
          connectThread.start()
        }
      }
    }
  }
}
private lateinit var device: BluetoothDevice

ConnectThread 类在这里:

private inner class ConnectThread(device: BluetoothDevice) : Thread() {

  private val mSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
    device.createRfcommSocketToServiceRecord(UUID)
  }

  override fun run() {
    bluetoothAdapter?.cancelDiscovery()
    mSocket?.use { socket ->
      socket.connect()
      toast("Connected!")
    }
  }

  fun cancel() {
    try {
      mSocket?.close()
    } catch (e: IOException) {
      Log.e(TAG, "Could not close the client socket", e)
    }
  }
}

UUID 给出为

private val UUID = nameUUIDFromBytes("49535343-...".toByteArray())

感谢您的时间和专业知识!

4

1 回答 1

0

正如我的一位目光敏锐的同事所指出的那样,蓝牙描述以官方 android 开发者网站上的“oldschool”版本开头。稍后,描述了我的项目需要的蓝牙低功耗。

于 2019-02-11T12:05:18.100 回答