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

Android CompanionDeviceManager过时方法替换及关联信息获取问题咨询

CompanionDeviceManager 适配现代Android API指南

1. 替换过时的startIntentSenderForResult为registerForActivityResult

直接使用ActivityResultContracts.StartIntentSenderForResult契约创建启动器,解决类型不匹配问题:

步骤1:定义ActivityResultLauncher

private val companionDeviceLauncher = registerForActivityResult(
    ActivityResultContracts.StartIntentSenderForResult()
) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        handleCompanionDeviceResult(result.data)
    }
}

步骤2:启动关联流程

将原来调用startIntentSenderForResult的代码替换为启动器的launch方法,注意传入IntentSenderRequest对象:

// 假设你已通过CompanionDeviceManager生成intentSender
val intentSenderRequest = IntentSenderRequest.Builder(intentSender).build()
companionDeviceLauncher.launch(intentSenderRequest)

2. 避免使用过时的结果获取API

弃用getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE)这类过时API,直接从返回Intent中获取AssociationInfo对象——这是官方推荐的现代方式,可直接关联到目标设备信息。

3. BLE设备场景下获取ScanResult

从返回Intent中提取AssociationInfo,再通过associatedDevice属性获取对应的ScanResult对象:

private fun handleCompanionDeviceResult(data: Intent?) {
    data ?: return
    
    // API 33+推荐写法:指定类型获取AssociationInfo
    val associationInfo = data.getParcelableExtra(
        CompanionDeviceManager.EXTRA_ASSOCIATION_INFO,
        AssociationInfo::class.java
    ) ?: return

    // BLE设备的关联设备类型为ScanResult,直接强转即可
    val bleScanResult = associationInfo.associatedDevice as? ScanResult
    bleScanResult?.let {
        // 提取BLE设备核心信息
        val device = it.device
        val deviceAddress = device.address
        val deviceName = device.name ?: "未知设备"
        
        // 执行后续BLE连接或关联逻辑
        connectToBleDevice(device)
    }
}

兼容低版本API(低于33)

如果需要适配API 33以下设备,可使用旧版getParcelableExtra方法并强转:

@Suppress("DEPRECATION")
val associationInfo = data.getParcelableExtra<AssociationInfo>(
    CompanionDeviceManager.EXTRA_ASSOCIATION_INFO
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:40:30