Search code examples
androidkotlinandroid-bluetoothkotlin-android-extensions

How to search paried devices Kotlin Android App


I am attempting to create an Android app to connect to a HC-05 Bluetooth module. I am going through the Android documentation, however, following the documentation I am receiving an error that I can not work around. I do not understand how to the list of bonded devices.

fun Bluetooth() {
    val pairedDevices: Set<BluetoothDevice>? = BluetoothAdapter.bondedDevices
    pairedDevices?.forEach { device ->
        val deviceName = device.name
        val deviceHardwareAddress = device.address // MAC address
    }

I am getting an error at the "= BluetoothAdapter.bondedDevices". I am trying to get the list of devices bonded to the Android phone and pick the HC-05 Bluetooth module to connect to.

I have tried reading through the documentation of the BluetoothAdapter and cannot figure out how to use the getBondedDevices() function. Any help would be appreciated greatly!


Solution

  • getBondedDevices() is not a static function. You need to use the following way to get the BluetoothAdapter first:

    val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    val bluetoothAdapter = bluetoothManager.adapter
    

    Deprecated way:

    val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    

    And then using bluetoothAdapter.bondedDevices should work.

    But note that you have to also add the following permission in AndroidManifest.xml:

    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />