上一篇博客 【Android Protobuf 序列化】Protobuf 使用 ( protoc 编译器简介 | 下载 protoc 编译器 | 使用 protoc 编译器编译 .proto 源文件 ) 中 , 在命令行中使用 protoc 编译器 , 将 .proto 源文件编译成了 Java 源文件 ;
Google 提供了专门用于编译 .proto 源文件的 Gradle 插件 protobuf-gradle-plugin ;
protobuf-gradle-plugin 项目地址 : https://github.com/google/protobuf-gradle-plugin
在 Android Studio 中 , 借助该 protobuf-gradle-plugin Gradle 插件 , 可以自动完成 Protobuf 源文件的编译工作 ;
protobuf-gradle-plugin 插件配置方法 , 参考 https://github.com/google/protobuf-gradle-plugin 项目主页的 MarkDown 文档 ;
protobuf-gradle-plugin 插件配置 :
mavenCentral()
,在 Project 的 build.gradle 中进行如下配置 :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.16'
}
}
在 Module 的 build.gradle 中进行如下配置 :
apply plugin: 'com.android.application' // or 'com.android.library'
apply plugin: 'com.google.protobuf'
如果使用 Protobuf 3.0 ~ 3.7 之间的版本 , 使用的是 protobuf-lite 版本 , 该版本相对于普通的 Protobuf , 生成的源文件更精简 , 这是为了适配在 Android 设备上使用而定制的 , 更适合移动端使用 ;
dependencies {
// You need to depend on the lite runtime library, not protobuf-java
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 { }
}
}
}
}
如果使用 Protobuf 3.8 之后的版本 , 使用如下设置 :
dependencies {
// You need to depend on the lite runtime library, not protobuf-java
implementation 'com.google.protobuf:protobuf-javalite:3.8.0'
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.8.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option "lite"
}
}
}
}
}
配置完成后 , 选择 " 菜单栏 / Build / Make Project " 编译整个工程 ,
编译完成后 , 在 " app\build\generated\source\proto\debug\javalite " 目录下生成 Protobuf 源码对应的 Java 类 , AddressBook.java 源文件生成在 " app\build\generated\source\proto\debug\javalite\com\example\tutorial\protos " 目录中 ;
Android Studio 会将 Protobuf 生成的这些 Java 类引入到当前项目的 Classpath 中 , 并打包到 APK 中 , 在开发时 , 可以引用这些类 ;
Protobuf 参考资料 :
博客源码 :