androidandroid-bluetooth

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) {}

Solution

  • 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.