Home > other >  Show connected bluetooth devices Kotlin
Show connected bluetooth devices Kotlin

Time:03-02

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

CodePudding user response:

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

CodePudding user response:

@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

  • Related