39

How do I fix the deprecation warning in this code? Alternatively, are there any other options for doing this? enter image description here

   val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            if (mBluetoothAdapter.isEnabled) {}

2 Answers2

83

As you can see here, they now recommend this:

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

The reason seems to be that BluetoothAdapter.getDefaultAdapter() ignores Context, while more complex apps might need to explicitly reference the correct Context.

Not a good reason to deprecate it in my opinion, as I can't think of a realistic/frequent usecase where the BluetoothAdapter needs to be based on the Context. They should have just left both options (Context based and default) in without deprecation.

Merthan Erdem
  • 5,598
  • 2
  • 22
  • 29
0
    BluetoothManager bluetoothManager = (BluetoothManager) YourContext.getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
Ton
  • 9,235
  • 15
  • 59
  • 103