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

Android Studio构建项目时出现Duplicate class found错误求助

解决Google Cloud Language依赖的重复类与缺失依赖问题

问题背景

添加com.google.cloud:google-cloud-language:2.34.0依赖后,Android Studio出现Duplicate class found错误;若给该依赖添加exclude(module = "protobuf-java"),错误消失,但代码中无法访问Document和AnalyzeSentimentRequest,提示缺少com.google.protobuf.GeneratedMessageV3依赖。

可行解决方案

方案1:强制统一Protobuf版本

项目中其他依赖(如Firebase、Google Places等)可能引入了不同版本的Protobuf,导致版本冲突。通过强制指定Protobuf版本,可同时解决重复类和缺失依赖问题:

在build.gradle.kts (:app)中添加版本强制策略,放在dependencies块外部:

configurations.all {
    // 选择与google-cloud-language:2.34.0兼容的Protobuf版本,可根据实际调整
    resolutionStrategy.force("com.google.protobuf:protobuf-java:3.25.3")
}

保留原google-cloud-language依赖(无需exclude):

implementation("com.google.cloud:google-cloud-language:2.34.0")

方案2:改用Firebase ML Kit情感分析(推荐)

Google Cloud Language客户端库更适用于后端服务,Android端推荐使用Firebase ML Kit的情感分析功能,它专为移动端优化,依赖冲突更少:

  1. 移除com.google.cloud:google-cloud-language:2.34.0依赖
  2. 添加Firebase ML Kit相关依赖:
implementation("com.google.firebase:firebase-ml-natural-language:22.0.1")
implementation("com.google.firebase:firebase-ml-natural-language-sentiment-model:20.0.7")
  1. 修改情感分析代码(适配异步特性,推荐用协程):
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage
import com.google.firebase.ml.naturallanguage.sentiment.FirebaseSentiment
import kotlinx.coroutines.suspendCoroutine

suspend fun getSentimentScore(text: String?): Float = suspendCoroutine { cont ->
    if (text.isNullOrEmpty()) {
        cont.resume(0.0f)
        return@suspendCoroutine
    }

    FirebaseNaturalLanguage.getInstance()
        .sentimentAnalysisModel
        .analyzeSentiment(text)
        .addOnSuccessListener { result: FirebaseSentiment ->
            val score = result.score
            Log.d("SENTIMENT", "THE SENTIMENT OF '$text' IS: $score")
            cont.resume(score)
        }
        .addOnFailureListener { e ->
            Log.d("SENTIMENT", "COULD NOT GET SENTIMENT SCORE :${e.message}")
            cont.resume(0.0f)
        }
}

方案3:针对性排除冲突依赖中的Protobuf

通过依赖树定位重复Protobuf的来源,只排除其他依赖中的冲突版本,保留google-cloud-language的Protobuf:

  1. 执行命令查看依赖树:
./gradlew app:dependencies
  1. 找到所有引入protobuf-java的依赖,例如发现Firebase Firestore引入了冲突版本,就单独排除它的Protobuf:
implementation("com.google.firebase:firebase-firestore-ktx") {
    exclude(module = "protobuf-java")
}

保留原google-cloud-language依赖即可正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:04:56