skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    @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


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search