You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BluetoothAdapter.getDefaultAdapter()已弃用 应使用什么替代及修复弃用警告

Android蓝牙弃用API替换方案

官方推荐替代API

自Android 12(API等级31)开始,BluetoothAdapter.getDefaultAdapter() 被正式弃用,官方推荐通过系统服务BluetoothManager获取BluetoothAdapter实例,该服务自API 18起就已加入系统,可覆盖绝大多数现有设备。

原有代码修复方案

修复后的Kotlin代码如下,可直接解决弃用警告:

// 获取蓝牙管理器实例
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val mBluetoothAdapter = bluetoothManager.adapter
// 非空判断后读取蓝牙状态
// Android 12及以上调用isEnabled需要提前申请BLUETOOTH_CONNECT权限
if (mBluetoothAdapter?.isEnabled == true) {
    // 原有业务逻辑
}

如果你的应用minSdkVersion低于18,需要增加版本兼容逻辑:

val mBluetoothAdapter = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
    val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    bluetoothManager.adapter
} else {
    // 低版本继续使用原有API
    BluetoothAdapter.getDefaultAdapter()
}
if (mBluetoothAdapter?.isEnabled == true) {
    // 原有业务逻辑
}

其他实现相同功能的可选方案

  • 若需要长期监听蓝牙开关状态,可注册BluetoothAdapter.ACTION_STATE_CHANGED广播接收状态变化回调,无需主动获取Adapter实例即可实时获取蓝牙状态变更。
  • 若仅需要触发蓝牙开启操作,可直接调用系统内置的开启蓝牙的Intent跳转:
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)

注意事项

  • Android 12及以上版本调用蓝牙状态读取、连接相关接口前,需要先动态申请BLUETOOTH_CONNECT权限,否则会触发运行时异常。
  • 若设备本身不支持蓝牙功能,获取到的BluetoothAdapter实例会为null,必须做非空判断避免空指针崩溃。

内容的提问来源于stack exchange,提问作者user15460872

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:45:01