首页 > 解决方案 > 现在不推荐使用 BluetoothAdapter.getDefaultAdapter() 我该使用什么?

问题描述

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

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

标签: androidandroid-bluetooth

解决方案


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

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

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

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


推荐阅读