如何使用已弃用的方法克服 Android CompanionDataManager?

问题描述 投票:0回答:1

在其自己的文档页面中,指出 CompanionDeviceManager 是扫描设备的首选机制,而无需请求臭名昭著的 FINE_LOCATION 权限。

deviceManager.associate(pairingRequest, new CompanionDeviceManager.Callback() {
    executor,
    // Called when a device is found. Launch the IntentSender so the user can
    // select the device they want to pair with.
    @Override
    public void onDeviceFound(IntentSender chooserLauncher) {
        try {
            startIntentSenderForResult(
                    chooserLauncher, SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0
            );
        } catch (IntentSender.SendIntentException e) {
            Log.e("MainActivity", "Failed to send intent");
        }
    }

不幸的是,这段代码存在各种问题。对于初学者来说,它不能立即编译,因为您必须移动

executor
参数。而且,即使在编写它时,它也使用了大量已弃用的方法。

第一个已弃用的方法位于

onAssociationPending()
startIntentSenderForResult
。长期以来,文档们付出了很大的努力来抹黑这个机制。然后我将代码转换为:

LAUNCH_DEVICE_CHOOSER_ASSOCIATION.launch( chooserLauncher );

及其对应物:

private final ActivityResultLauncher<IntentSender> LAUNCH_DEVICE_CHOOSER_ASSOCIATION =
            this.registerForActivityResult(
                    new ActivityResultContracts.StartIntentSenderForResult(),
                    result -> {
                        if ( result.getResultCode() == RESULT_OK ) {
                            final BluetoothDevice DEVICE =
                                    result.getData().getParcelableExtra( CompanionDeviceManager.EXTRA_DEVICE );
                            if ( DEVICE != null ) {
                                this.onDeviceFound( DEVICE );
                            }
                        }
                    });

不过,这段代码存在各种问题:

  • 编译器抱怨提供了

    ActivityResultLauncher<IntentSenderResquest>
    ,而不是
    ActivityResultLauncher<IntentSender>
    。我不明白为什么。如果我将
    ActivityResultLauncher<IntentSender>
    更改为
    ActivityResultLauncher<IntentSenderRequest>
    ,那么它会编译,但是当需要
    launch()
    时,方法
    IntentSender
    会抱怨传递
    IntentSenderRequest

  • 在上面的代码中,

    result.getData()
    返回一个
    Intent
    。这个类预计有一个
    getParcelableExtra()
    方法,但已被弃用。但这还不是全部,该方法的参数应该是
    CompanionDeviceManager.EXTRA_DEVICE
    ,你猜对了,它已被弃用。在后者的文档中,建议使用
    AssociationInfo::getAssociatedDevice
    ,这是突然产生的方法。我的意思是,无处可寻(至少我无法找到它),如何到达该类的对象。

我的问题是:

  • 此代码如何转换为(据称)更新/更清洁/更安全的
    registerForActivityResult
    机制?
  • 如何从
    ActivityResult
    对象获取额外信息,避免弃用的机制?
  • 更好的是,我应该获得一个
    AssociationInfo
    对象,我应该调用
    getAssociatedDevice()
    ,从中我应该获得一个
    ScanResult
    对象,因为我正在过滤 BLE 设备。我怎样才能从
    result.getData()
    (一个
    Ìntent
    )得到它?

任何帮助将不胜感激。

java android android-bluetooth
1个回答
0
投票

您的 Android 版本是什么?在 Android 13 及更高版本上,除了活动结果中的 BluetoothDevice 之外,您还应该获得带有 AssociationInfo 的 onAssociationCreated 回调。

© www.soinside.com 2019 - 2024. All rights reserved.