我正在Kotlin开发android应用程序,我正试图在我的应用程序中获得用于蓝牙通信的蓝牙适配器。
我读过以下文档:设置蓝牙
如图所示,我需要编写以下代码来获得适配器:
val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}
当我在Android中写这篇文章时,我收到了这样的警告:
'getDefaultAdapter(): BluetoothAdapter!' is deprecated. Deprecated in Java
...
Deprecated: this method will continue to work, but developers are
strongly encouraged to migrate to using BluetoothManager.getAdapter(), since that
approach enables support for Context.createAttributionContext.
我试过像这样使用新的推荐方法
var bluetoothManager = (BluetoothManager)(Context.getSystemService(Context.BLUETOOTH_SERVICE))
var adapter = bluetoothManager.getAdapter()
我在代码中发现了一个错误:
Unresolved reference: getSystemService
我尝试过更多的方法来实现它--什么也没成功。
我很乐意得到一些帮助。
请指点。
谢谢
发布于 2022-10-14 13:02:37
如果您支持较旧的API,则应该使用ContextCompat.getSystemService(this, BluetoothManager::class.java)
(其中this
是从Context
检索服务的Context
)。在此之后,您可以访问BluetoothAdapter
。
我创建了一个扩展函数,用于获取适配器:
fun Context.bluetoothAdapter(): BluetoothAdapter? =
ContextCompat.getSystemService(this, BluetoothManager::class.java).adapter
如果您的目标是更高的API(超过23),您可以安全地直接使用上下文:
fun Context.bluetoothAdapter(): BluetoothAdapter? =
(this.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
https://stackoverflow.com/questions/70475132
复制相似问题