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

在Kotlin中实现蓝牙设备连接状态检测与弹窗逻辑

蓝牙连接状态判断逻辑完善

根据需求,直接替换原有IF语句的判断逻辑,结合两种常见蓝牙连接场景给出落地代码:

场景1:经典蓝牙设备连接判断

假设你持有目标蓝牙设备的BluetoothDevice实例(targetDevice),通过设备内置状态字段判断连接状态:

testbutton.setOnClickListener{
    // 校验设备已配对且处于活跃连接状态
    val isConnected = targetDevice.bondState == BluetoothDevice.BOND_BONDED && 
                      targetDevice.connectionState == BluetoothDevice.STATE_CONNECTED
                      
    if(isConnected){
        // 连接正常,无弹窗操作
    }else{
        bluetoothDialog.show()
        // 调用你已实现的蓝牙重连方法
        reconnectBluetoothDevice()
    }
}

场景2:BLE蓝牙(Gatt)连接判断

若使用BLE蓝牙且持有BluetoothGatt实例(bluetoothGatt),通过Gatt连接状态判断:

testbutton.setOnClickListener{
    // 校验Gatt实例有效且处于连接状态
    val isConnected = bluetoothGatt != null && 
                      bluetoothGatt.connectionState == BluetoothGatt.STATE_CONNECTED
                      
    if(isConnected){
        // 连接正常,无弹窗操作
    }else{
        bluetoothDialog.show()
        // 调用你已实现的蓝牙重连方法
        reconnectBluetoothDevice()
    }
}

注意事项

  • 替换代码中的targetDevice/bluetoothGatt为你项目中实际的设备实例
  • reconnectBluetoothDevice()替换为你已实现的重连逻辑方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:55:16