升级Braintree Data Collector至4.31.0后遇编译及类型推断问题求助
解决Braintree Data Collector 4.31.0升级问题
一、修复重复类编译错误(Execution failed for task ':checkDebugDuplicateClasses')
- 彻底移除旧版本依赖:检查项目所有
build.gradle文件(Module级和Project级),删除所有3.x版本的Braintree相关依赖项,只保留4.31.0版本的核心库和数据收集库:implementation 'com.braintreepayments.api:core:4.31.0' implementation 'com.braintreepayments.api:data-collector:4.31.0' - 排查并排除重复依赖:执行gradle依赖树命令查看依赖来源:
若发现第三方库依赖了旧版Braintree组件,在对应依赖中添加排除规则:./gradlew app:dependenciesimplementation('com.example:third-party-lib:1.0.0') { exclude group: 'com.braintreepayments.api', module: 'data-collector' exclude group: 'com.braintreepayments.api', module: 'core' } - 清理缓存并重建:执行命令清理gradle缓存,或通过Android Studio的
File > Invalidate Caches... > Invalidate and Restart操作:./gradlew clean build --refresh-dependencies
二、修复类型推断错误并适配4.x API
Braintree 4.x版本彻底重构了API,原BraintreeFragment已被弃用,需替换为BraintreeClient,同时回调接口格式也发生变化:
重构后的完整代码
override fun getDeviceData(activity: AppCompatActivity, config: String): Result<String> { val deviceDataBox = ArrayBlockingQueue<Result<String>>(1) // 初始化4.x版本的BraintreeClient,替代旧版BraintreeFragment val braintreeClient = BraintreeClient(activity, config) // 显式指定回调参数类型,解决类型推断错误 DataCollector.collectDeviceData(braintreeClient) { deviceData: String?, error: Exception? -> when { deviceData != null -> { print(deviceData) deviceDataBox.put(Result.Valid(deviceData)) } error != null -> { deviceDataBox.put(Result.Error(error)) // 需确保Result类包含Error分支 } else -> { deviceDataBox.put(Result.Error(IllegalStateException("Unknown error occurred"))) } } } return deviceDataBox.take() }
关键说明
- 原
DataCollector.collectDeviceData方法的参数从BraintreeFragment改为BraintreeClient,这是4.x的核心变化。 - 回调lambda需显式声明参数类型(
deviceData: String?,error: Exception?),解决类型推断失败的问题。 - 需确保自定义的
Result类包含Valid和Error两种状态,用于封装成功或失败的结果。
内容的提问来源于stack exchange,提问作者Sai Sankar
相关产品推荐
相关产品推荐

