现在BluetoothAdapter.getDefaultAdapter()被弃用了,那我现在应该使用什么?

41

这段代码中如何修复弃用警告?或者还有其他选项可以实现此功能吗?

在这里输入图片描述
   val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            if (mBluetoothAdapter.isEnabled) {}

你正在使用哪个Java版本? - SoufianeKre
2个回答

89

正如您可以在这里看到的,他们现在推荐使用:

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

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

在我看来,这不是废弃它的好理由,因为我想不出一个现实/频繁的用例需要基于Context的BluetoothAdapter。他们应该保留两个选项(基于Context和默认)而不进行废弃。


2
    BluetoothManager bluetoothManager = (BluetoothManager) YourContext.getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接