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

Android DataStore:Gradle未生成Protobuf类问题求助

问题排查与解决

1. 缺少Protobuf Gradle插件配置

Datastore依赖Protobuf生成对应Java类,必须先在项目根目录的构建脚本中添加Protobuf插件:

根目录build.gradle(Groovy)

buildscript {
    dependencies {
        classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.24"
    }
}

根目录build.gradle.kts(Kotlin DSL)

buildscript {
    dependencies {
        classpath("com.google.protobuf:protobuf-gradle-plugin:0.8.24")
    }
}

接着在app模块的构建脚本中应用插件:

app模块build.gradle(Groovy)

plugins {
    id 'com.android.application'
    id 'com.google.protobuf' // 添加这行
}

app模块build.gradle.kts(Kotlin DSL)

plugins {
    id("com.android.application")
    id("com.google.protobuf") // 添加这行
}

2. 补充Protobuf核心依赖

仅引入Datastore依赖不足以生成类,需添加Protobuf Java Lite库到app模块:

app模块build.gradle(Groovy)

dependencies {
    implementation "androidx.datastore:datastore:1.0.0"
    implementation "com.google.protobuf:protobuf-javalite:3.24.4" // 新增依赖
}

app模块build.gradle.kts(Kotlin DSL)

dependencies {
    implementation("androidx.datastore:datastore:1.0.0")
    implementation("com.google.protobuf:protobuf-javalite:3.24.4") // 新增依赖
}

3. 配置Protobuf生成规则(建议)

在app模块构建脚本中指定生成适配Android的Lite版本代码:

app模块build.gradle(Groovy)

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.24.4"
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option 'lite'
                }
            }
        }
    }
}

app模块build.gradle.kts(Kotlin DSL)

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.24.4"
    }
    generateProtoTasks {
        all().forEach { task ->
            task.builtins {
                create("java") {
                    option("lite")
                }
            }
        }
    }
}

完成以上配置后,执行Build > Rebuild Project,生成的WorkItemVO类会出现在build/generated/source/proto/debug/java/com/freedom/android/config/work/目录下。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:12:46