Question

What do I use now that BluetoothAdapter.getDefaultAdapter() is deprecated?

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) {}
 48  27103  48
1 Jan 1970

Solution

 102

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 and use Context.createAttributionContext.

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 a tagged Context. They should have just left both options (Context based and default) in without deprecation.

2021-09-09

Solution

 5
    BluetoothManager bluetoothManager = (BluetoothManager) YourContext.getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
2022-04-14