Android with Kotlin, can't get the BluetoothAdapter

86 Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST ANSWER

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
0
On

I followed Tom Truyen suggestion and troubleshooted a newly arisen malfunction according this , and it worked as follows

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