Om Keshwani
Om Keshwani

Reputation: 11

Android- implemented Bluetooth connection code but does not work on other Android device

I am working on an Android app that connects to a Bluetooth device using BluetoothSocket. However, when I attempt to connect, I get the following error: it works when i try to connect with laptop's bluetooth from but fail when try connect with another android device(redmi a2 (Androdi os 13))

Attempting to connect... Attempt 3
connect() for device XX:XX:XX:XX:69:7D called by pid: 5069
read failed, socket might be closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:1079)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:588)
at com.sample.BluetoothUtil$ConnectThread.run(BluetoothUtil.kt:156)

Current Implementation

Here is the ConnectThread I am using to establish the Bluetooth connection:

private inner class ConnectThread(val device: BluetoothDevice?) : Thread() {
private val connectionUUID = device?.getUuids()?.get(0)?.getUuid()
private var bluetoothSocket: BluetoothSocket? = null

override fun run() {
    dataObjects.bluetoothAdapter?.cancelDiscovery()

    bluetoothSocket = device?.createInsecureRfcommSocketToServiceRecord(connectionUUID)
    bluetoothSocket?.let { socket ->
        try {
            val maxRetries = 3
            var attemptCount = 0

            while (!connectionAttempted && attemptCount < maxRetries) {
                try {
                    Log.d("BLUETOOTH_CONNECT", "Attempting to connect... Attempt ${attemptCount + 1}")
                    isConnecting = true

                    // Wait for bonding to complete if in progress
                    while (device?.bondState == BluetoothDevice.BOND_BONDING) {
                        Thread.sleep(100)
                    }

                    socket.connect()
                    connectionAttempted = true
                    Log.d("BLUETOOTH_CONNECT", "Connection successful")
                    showToast("Connected to ${device?.name ?: "device"}")
                    return
                } catch (e: IOException) {
                    Log.e("BLUETOOTH_CONNECT", "Connection attempt failed", e)
                    attemptCount++
                    isConnecting = false
                    if (attemptCount < maxRetries) {
                        Thread.sleep(1000)
                    }
                }
            }

            if (!connectionAttempted) {
                Log.e("BLUETOOTH_CONNECT", "Failed to connect after $maxRetries attempts")
                showToast("Failed to connect after several attempts")
                cancel()
            }
        } catch (e: Exception) {
            Log.e("BLUETOOTH_CONNECT", "Connection error", e)
            showToast("Connection error: ${e.localizedMessage}")
            isConnecting = false
            cancel()
        }
    } ?: run {
        Log.e("BLUETOOTH_CONNECT", "Socket is null")
        showToast("Error: Could not create Bluetooth socket")
    }
}

fun cancel() {
    try {
        isConnecting = false
        connectionAttempted = false
        bluetoothSocket?.close()
    } catch (e: Exception) {
        Log.e("BLUETOOTH_CONNECT", "Could not close socket", e)
    }
}
}

fun connectToDevice(device: BluetoothDevice?) {
var connectThread: ConnectThread? = null
connectThread?.cancel()
connectThread = ConnectThread(device)
connectThread.start()
}

Upvotes: 1

Views: 32

Answers (0)

Related Questions