Android-启动蓝牙套接字-连接超时

时间:2019-01-28 10:50:19

标签: android kotlin bluetooth bluetooth-socket

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

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

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

Translate.TranslateOption.targetLanguage(setLanguage)

ConnectThread类在这里:

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

UUID为

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)
    }
  }
}

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

1 个答案:

答案 0 :(得分:0)

正如我一位老鹰眼的同事所指出的那样,蓝牙描述始于官方android开发人员网站上的"oldschool" version。稍后介绍bluetooth low energy,这是我的项目所需要的。