androidkotlinbluetoothadapter

Android with Kotlin, can't get the BluetoothAdapter


I follow the instructions in https://developer.android.com/develop/connectivity/bluetooth/setup , trying to setup Bluetooth. When I am trying to get the BluetoothAdapter,

val bluetoothManager: BluetoothManager? = 
getSystemService(BluetoothManager::class.java)
val bluetoothAdapter: BluetoothAdapter? = bluetoothManager?.getAdapter()
if (bluetoothAdapter == null) {
    // Device doesn't support Bluetooth
}

I get the error

Type mismatch: inferred type is Class<BluetoothManager> but Context was expected

How can I work it around. Anyone?


Solution

  • You are using the getSystemService incorrectly

    It must be done like this:

    val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    

    Then you can get the adapter like this:

    val adapter = bluetoothManager.adapter