0

一切都可以使用按钮直接连接到蓝牙设备,但是当我使用 socket?.close 功能断开连接时,它不会重新连接,直到我重新启动 App .. 请帮忙

内部类 BtConnectThread : Thread() {

    val MY_UUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
    private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()


    private val blueSocket = bluetoothAdapter?.getRemoteDevice("00:19:10:08:4D:F0")
        ?.createRfcommSocketToServiceRecord(MY_UUID)


    override fun run() {
        requireActivity().runOnUiThread {
           bluetoothAdapter?.cancelDiscovery()
            try {
                blueSocket?.connect()
                Toast.makeText(requireContext(), "Connect Success", Toast.LENGTH_SHORT).show()
                btConnected = true

            } catch (e: IOException) {
                Toast.makeText(requireContext(), "Connect Failed", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun write(bytes: ByteArray) {
        requireActivity().runOnUiThread {
            try {
                btOutStream.write(bytes)
                Toast.makeText(requireContext(), "Sent Success", Toast.LENGTH_SHORT).show()
            } catch (e: IOException) {
                Toast.makeText(requireContext(), "Sending Failure", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun cancel() {
        requireActivity().runOnUiThread {
            try {
                blueSocket?.close()
                Toast.makeText(requireContext(), "Disconnected", Toast.LENGTH_SHORT).show()
                btConnected = false
            } catch (e: IOException) {
                Toast.makeText(requireContext(), "Failed To Disconnect", Toast.LENGTH_SHORT).show()

            }
        }
    }

}
4

0 回答 0