蓝牙客户端Socket每次得到相同的异常

我正在写一个Android应用程序,主要是在Kotlin应该扫描蓝牙设备,并与他们配对。 我也希望它在后台运行一个蓝牙服务器套接字来等待连接尝试。 不过,当我试图调用BluetoothSocket.connect()方法时,我仍然遇到了同样的异常。 例外是:

 10-10 20:07:57.917 18643-27894/com.example.zemcd.toofxchange E/Pairing Thread: error connecting java.io.IOException: read failed, socket might closed or timeout, read ret: -1 at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:754) at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:766) at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:388) at com.example.zemcd.toofxchange.PairingThread.run(BluetoothUtils.kt:83) 

我读到,这可以解决类似的代码

 btSocket = device.javaClass.getMethod("createRFcommSocket", Int::class).invoke(device, 1) as BluetoothSocket 

但是这不起作用。 它导致应用程序崩溃,由NoSuchMethod引起的ReflectException 。 此外,我已经读过,这不是一个原因发布的方法,我想尝试使用发布的createRFcommSocketToServiceRecord()方法。 我不确定从哪里去,或者是什么导致IOException 。 此外,我甚至从来没有去配对屏幕。 我试图找出这个异常的原因,以及如何解决这个问题。 我的代码:

 class BluetoothUtils { companion object { val _UUID = UUID.fromString("a0e7e4c7-0e4e-43b7-9d18-659192512164") val TAG = "BluetoothUtils" fun initPairingServer(adapter: BluetoothAdapter){ var mmServerSocket: BluetoothServerSocket? = null try { var tmp = adapter.listenUsingRfcommWithServiceRecord(TAG, _UUID) mmServerSocket = tmp ListenThread(mmServerSocket).start() }catch (ioe: IOException){ Log.e(TAG, "Error initializing Bluetooth", ioe) } } fun pair(adapter: BluetoothAdapter, device: BluetoothDevice){ var btSocket: BluetoothSocket? = null try { adapter.cancelDiscovery() btSocket = device.createRfcommSocketToServiceRecord(_UUID) PairingThread(btSocket).start() }catch (ioe: IOException){ Log.e(TAG, "error connecting", ioe) } } } } class ListenThread(val btServSock: BluetoothServerSocket) : Thread(){ companion object { val TAG = "ListenThread" } var btSocket: BluetoothSocket? = null override fun run() { super.run() while (true){ try { Log.d(TAG, "listening . . . ") btSocket = btServSock.accept() }catch (ioe: IOException){ Log.e(TAG, "Error", ioe) break } //manage connection here //with either BluetoothUtils function //or BluetoothSocket extension } } } class PairingThread(val btSocket: BluetoothSocket) : Thread(){ companion object { val TAG = "Pairing Thread" } override fun run() { super.run() try { Log.d(TAG, "attempting to connect") btSocket.connect() }catch (ioe: IOException){ Log.e(TAG, "error connecting", ioe) btSocket.close() } } } 

请有人帮我找到我的问题。 难道是我试图连接到不使用相同UUID的设备? 我只是想连接到我的笔记本电脑。