mohammed_sajid
mohammed_sajid

Reputation: 435

Show connected bluetooth devices Kotlin

I can only find how to show paired bluetooth devices and not the current connected bluetooth devices. This is the code to show paired:

val blueToothManager=applicationContext.getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
    val bluetoothAdapter=blueToothManager.adapter
    var pairedDevices = bluetoothAdapter.bondedDevices
    var data:StringBuffer = StringBuffer()
    for(device: BluetoothDevice in pairedDevices)
    {
        data.append(device.name + " ")
    }
    if(data.isEmpty())
    {
        bluetoothText.text = "0 Devices Connected"
        val leftDrawable: Drawable? = getDrawable(R.drawable.ic_bluetooth_disabled)
        val drawables: Array<Drawable> = bluetoothText.getCompoundDrawables()
        bluetoothText.setCompoundDrawablesWithIntrinsicBounds(
            leftDrawable, drawables[1],
            drawables[2], drawables[3]
        )
    }
    else
    {
        bluetoothText.text = data
        val leftDrawable: Drawable? = getDrawable(R.drawable.ic_bluetooth_connected)
        val drawables: Array<Drawable> = bluetoothText.getCompoundDrawables()
        bluetoothText.setCompoundDrawablesWithIntrinsicBounds(
            leftDrawable, drawables[1],
            drawables[2], drawables[3]
        )
    }

Anybody know how to show current connected bluetooth devices and not paired devices? Thanks

Upvotes: 2

Views: 3497

Answers (2)

mohammed_sajid
mohammed_sajid

Reputation: 435

@Mohamed Saleh, thanks that worked. I added this:

private fun isConnected(device: BluetoothDevice): Boolean {
    return try {
        val m: Method = device.javaClass.getMethod("isConnected")
        m.invoke(device) as Boolean
    } catch (e: Exception) {
        throw IllegalStateException(e)
    }
}

and changed this:

for(device in pairedDevices)
{
    if(isConnected((device)))
        data.append(" " + device.name + " ")
}

It now shows the connected bluetooth device and not the paired devices! Also thanks @Abdallah AbuSalah from the other post: Android bluetooth get connected devices

Upvotes: 2

Mohamed Saleh
Mohamed Saleh

Reputation: 141

I don't think there is a direct way to check if paired bluetooth device is connected or not because it is something that can be changed anytime .. the best solution I can suggest is to list all paired devices and using a Broadcast receiver that return the status of bluetooth change the specified device in the list as mentioned in the following link Android bluetooth get connected devices

Upvotes: 2

Related Questions