Gradle 找不到 protobuf 生成的类(Android DataStore)

Sag*_*tus 3 android-studio android-jetpack-datastore

我是参考文档引入了依赖

implementation "androidx.datastore:datastore:1.0.0"
Run Code Online (Sandbox Code Playgroud)

然后定义架构app/src/main/proto/.proto

syntax = "proto3";

option java_package = "com.freedom.android.config.work";
option java_multiple_files = true;

message WorkItemVO {
  
  bool enabled = 1;
  
  string title = 2;
  
  string repeat_interval = 3;
  string repeat_interval_timeUnit = 4;
  
  string last_update_time = 5;
  string last_update_result = 6;
}
Run Code Online (Sandbox Code Playgroud)

之后app build,却build/generated/source/proto/没有生成WorkItemVOclass文件。

你能告诉我我错过了什么吗?

小智 6

Android 开发指南重点关注直接依赖项以及如何使用 proto 存储,而没有提及 protobuf java 类的生成。使用 Proto DataStore 的Codelab 提供了完整的示例

在此 Codelab 中,您可以看到 gradle 上需要进行特定配置:

plugins {
    ...
    id "com.google.protobuf" version "0.8.17"
}

dependencies {
    implementation  "androidx.datastore:datastore:1.0.0"
    implementation  "com.google.protobuf:protobuf-javalite:3.18.0"
    ...
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:21.7"
    }

    // Generates the java Protobuf-lite code for the Protobufs in this project. See
    // https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
    // for more information.
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option 'lite'
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,版本号需要更新。

对于像我这样使用带有 kotlin 语法的 gradle 版本目录的人,您必须对 3 个文件进行操作: lib.versions.yml

[versions]
protobuf-javalite = "3.23.3"
protobuf-plugin = "0.9.3"

[libraries]
protobuf-javalite = {module = "com.google.protobuf:protobuf-javalite", version.ref = "protobuf-javalite"}

[plugins]
protobuf = { id = "com.google.protobuf", version.ref = "protobuf-plugin"}
Run Code Online (Sandbox Code Playgroud)

build.gradle.kts(项目)

plugins {
  alias(libs.plugins.protobuf) apply false
}
Run Code Online (Sandbox Code Playgroud)

构建.gradle.kts(应用程序)

plugins {
    ...
    alias(libs.plugins.protobuf)
}
dependencies {
   ...
    implementation(libs.protobuf.javalite)
}
protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.23.2"
    }

    // Generates the java Protobuf-lite code for the Protobufs in this project. See
    // https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
    // for more information.
    generateProtoTasks {
        all().forEach { task ->
            task.builtins {
                create("java") {
                    option("lite")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

完成后,同步您的 gradle 项目并构建。您应该看到您的类已正确创建。

希望能帮助到你。