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

问题描述 投票:0回答:2

如何修复此代码中的弃用警告?或者,还有其他选择吗?

   val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            if (mBluetoothAdapter.isEnabled) {}
android android-bluetooth
2个回答
90
投票

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

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

原因似乎是

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

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


2
投票
    BluetoothManager bluetoothManager = (BluetoothManager) YourContext.getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
© www.soinside.com 2019 - 2024. All rights reserved.