必读
因gradle8.0有部分api不能用,本配置不适用于gradle 8.0及以上的版本
build.gradle 配置
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'com.google.protobuf'
}
android {
sourceSets {
main {
proto {
// 结构(.proto)文件所处路径,默认src/main/proto
srcDir 'src/main/proto'
}
}
}
}
dependencies {
// Protocol Buffers 的完整实现,提供了全部的功能和特性
implementation 'com.google.protobuf:protobuf-java:3.19.3'
// Protocol Buffers 的轻量级实现,支持 Proto3 语法
// implementation 'com.google.protobuf:protobuf-lite:3.0.0'
}
protobuf {
protoc {
// You still need protoc like in the non-Android case
artifact = 'com.google.protobuf:protoc:3.7.0'
}
// plugins {
// javalite {
// // The codegen for lite comes as a separate artifact
// artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
// }
// }
generateProtoTasks {
all().each { task ->
task.builtins {
// In most cases you don't need the full Java output
// if you use the lite output.
remove java
}
task.plugins {
// javalite { }
java {}
}
}
}
}
settings.gradle 配置
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.19'
}
}
proto结构
// 指定protobuf版本
syntax = "proto3";
// 命名空间,不影响生成的java代码输入地址
package com.example.protobuf;
// 生成的java代码所在的包
option java_package="com.example.protobuf";
// 生成的java代码类名
option java_outer_classname="StudentBuf";
// 生成的java代码是否重写hashCode和equals方法
option java_generate_equals_and_hash=true;
// 定义的结构,结构语法 https://protobuf.dev/programming-guides/proto3/
message Student {
string name = 1;
}
序列化
val bytes = StudentBuf.Student.newBuilder().setName(txt).build().toByteArray()
化序列化
val stu = StudentBuf.Student.parseFrom(bytes)