Home > database >  How to search paried devices Kotlin Android App
How to search paried devices Kotlin Android App

Time:01-29

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!

CodePudding user response:

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" />

CodePudding user response:

This procedure has to be done on a phone with developer options enabled connected to the laptop.

I put a break point on the line if (address==myaddress) and I stepped through the list examining devices with the debugger I used evaluate expression .and once I saw mydevice I copied its address out and I also copied the UUID out and made it hard coded in app just to get it working. Full code Android project is here and a You tube of project coming later tonight or tomorrow just got it working a few days ago. Like and subscribe if you like model trains some arduino mostly old model trains with a touch of underground modern electronics.

private fun getMySocket(): BluetoothSocket? {
    val bluetoothManager: BluetoothManager =
        context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    if (danny117BTSocket == null) {
        if (checkSelfPermission(
                appC, android.Manifest.permission.BLUETOOTH_CONNECT
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            val ada = bluetoothManager.adapter
            ada.bondedDevices.forEach {
                if (it.address == myAddress) {
                    danny117BTSocket = it.createRfcommSocketToServiceRecord(MY_UUID)
                }
            }
        }
    }
  • Related