How can I get Bluetoothmanager of the device on Kotlin?

Asked

Viewed 60 times

-1

I am learning about Bluetooth in Kotlin and was reading this Google document about Bluetoothadapter https://developer.android.com/reference/android/bluetooth/BluetoothAdapter. I started implementing code for Android devices with API 6.0 (higher than JELLY_BEAN_MR1) and have some problems getting Bluetoothmanager. Here’s the code I’m working on:

lateinit var mBluetoothManager:BluetoothManager
fun foo(context:Context){
      this.mBluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE)
}

Android Studio shows that it is a type incompatibility (required: Bluetoothmanager, Founded: Any!). So, how can I get the instance of Bluetoothmanager, I did something wrong? Why I need to connect this way using Systemservice and not that way:

var mBluetoothManager = BluetoothManager()

?

1 answer

0

Because the method getSystemService is a method made to operate in a generic way and return any type of system service, not just a system manager bluetooth. In this way, the return of the method is Any! (Kotlin) / Object (Java).

Therefore, a conversion to the type of destination remains

this.mBluetoothManager = 
    context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager

Why I need to connect this way using Systemservice and not that way var mBluetoothManager = BluetoothManager()?

Because, in the second way, you would be creating an instance of BluetoothManager, but that’s not what you need. You need to get an instance from Context.

  • So when I change context I need to call getSystemService again?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.