0

I need to connect to a bluetooth device which acts as a server. I know its UUID (at least the device's documentation contains it). However, I get an exception when I try to connect to it. The discovery part takes place successfully.

In the following, I cite the relevant code parts.

Here is the discovery. After I successfully found my device, I try to connect to it.

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

The ConnectThread class is here:

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

The UUID was given as

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

Thanks for your time and expertise!

Horvath Adam
  • 67
  • 1
  • 6
  • Additional information: the server (the device) seems to operate normally, since the official app downloaded from the play can connect to it. – Horvath Adam Jan 28 '19 at 15:36

1 Answers1

0

As one of my eagle-eyed colleagues pointed out, the bluetooth description begins with the "oldschool" version on the official android developers site. Later, the bluetooth low energy is described, which I need for my project.

Horvath Adam
  • 67
  • 1
  • 6