Zaid
Zaid

Reputation: 11

Bluetooth connect/disconnect not working in flutter

I am developing a Flutter application that connects to Bluetooth earphones. While attempting to establish and manage the Bluetooth connection, I encounter the following error:

D/BluetoothSocket: close() this: XX:XX:XX:XX:F0:35, channel: 4, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@ceca686, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@d23eb47, mSocket: android.net.LocalSocket@9e4ff74 impl:android.net.LocalSocketImpl@40e4c9d fd:java.io.FileDescriptor@3dca512, mSocketState: INIT
E/BluetoothConnection: Couldn't establish Bluetooth connection with fallback method: read failed, socket might closed or timeout, read ret: -1
E/BluetoothConnection: java.io.IOException: read failed, socket might closed or timeout, read ret: -1

I have used fallback method as mentioned in some suggestion on stackoverflow still getting this error. This is snippet from method channel

private fun connectDevice(device: BluetoothDevice) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "Connecting to ${device.name}", Toast.LENGTH_SHORT).show()
        val MY_UUID = UUID.fromString("0000111e-0000-1000-8000-00805f9b34fb")
        
        CoroutineScope(Dispatchers.IO).launch {
            var socket: BluetoothSocket? = null

            try {
                // Attempt to create socket using UUID
                socket = device.createRfcommSocketToServiceRecord(MY_UUID)
                Log.d("BluetoothConnection", "Attempting to connect using UUID")

                try {
                    socket.connect()
                    Log.d("BluetoothConnection", "Successfully connected using UUID")
                } catch (e: IOException) {
                    Log.e("BluetoothConnection", "Failed to connect using UUID: ${e.message}", e)
                    try {
                        Log.d("BluetoothConnection", "Trying fallback method...")
                        socket.close()
                        val fallbackSocket = createFallbackRfcommSocket(device)
                        fallbackSocket.connect()
                        Log.d("BluetoothConnection", "Successfully connected using fallback method")
                        socket = fallbackSocket
                    } catch (e2: Exception) {
                        Log.e("BluetoothConnection", "Couldn't establish Bluetooth connection with fallback method: ${e2.message}", e2)
                    }
                }
            } catch (e: Exception) {
                Log.e("BluetoothConnection", "Error creating socket: ${e.message}", e)
            }

            if (socket != null && socket.isConnected) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@MainActivity, "Connected to ${device.name}", Toast.LENGTH_SHORT).show()
                }
            } else {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@MainActivity, "Failed to connect to ${device.name}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    } else {
        Toast.makeText(this, "Bluetooth connect permission not granted", Toast.LENGTH_SHORT).show()
    }
}

private fun createFallbackRfcommSocket(device: BluetoothDevice): BluetoothSocket {
    return try {
        val method: Method = device.javaClass.getMethod("createRfcommSocket", Int::class.javaPrimitiveType)
        method.invoke(device, 1) as BluetoothSocket
    } catch (e: Exception) {
        throw RuntimeException("Fallback method failed", e)
    }
}


    private fun disconnectDevice(device: BluetoothDevice) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
            // Disconnect logic here if needed
            // Note: The RFCOMM socket needs to be closed to disconnect the device.
            // This is a placeholder for disconnecting logic.
            Toast.makeText(this, "Disconnecting from ${device.name}", Toast.LENGTH_SHORT).show()
            // Assuming you have a way to access the corresponding socket:
            // socket.close()
            // connectedDevices.remove(device)
            // sendDeviceListToFlutter()
        } else {
            Toast.makeText(this, "Bluetooth connect permission not granted", Toast.LENGTH_SHORT).show()
        }
    }

I am expecting : device Connectivity work correctly

Upvotes: 0

Views: 89

Answers (0)

Related Questions