既然 BluetoothAdapter.getDefaultAdapter() 已被弃用,我该使用什么?

46 android android-bluetooth

如何修复此代码中的弃用警告?或者,还有其他选择吗? 在此输入图像描述

   val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            if (mBluetoothAdapter.isEnabled) {}
Run Code Online (Sandbox Code Playgroud)

Mer*_*n E 97

正如您在这里看到的,他们现在推荐这个:

val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothManager.getAdapter()
Run Code Online (Sandbox Code Playgroud)

原因似乎是BluetoothAdapter.getDefaultAdapter()忽略 Context,而更复杂的应用程序可能需要显式引用正确的 Context 并使用 Context.createAttributionContext。

在我看来,这不是弃用它的好理由,因为我无法想到蓝牙适配器需要基于标记上下文的现实/常见用例。他们应该保留这两个选项(基于上下文和默认)而不弃用。