1,环境配置
1.1 Project工程根目录build.gradle
添加Probuf插件版本信息和maven仓库
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.0"
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.13'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
1.2 Module目录的build.gradle
1.2.1 声明依赖的protobuf插件
- 方式一:
plugins {
id 'com.android.application'
id 'com.google.protobuf'
}
- 方式二
apply plugin:'com.android.application'
apply plugin: 'com.google.protobuf'
1.2.2 添加protobuf依赖
dependencies {
implementation 'com.google.protobuf:protobuf-javalite:3.8.0'
}
1.2.3 添加proto task配置
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.8.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option "lite"
}
}
}
}
}
1.2.4 指定protobuf路径
- 方式一:
android{
......//省略其他配置项
sourceSets {
main {
java {
srcDirs 'src/main/java'
}
proto {
srcDirs 'src/main/proto'
}
}
}
}
- 方式二:android默认路径和java文件夹同级proto目录
2,定义proto
定义server.proto
syntax = "proto2";
package com.xxx.server;
message Server {
optional string addr = 1;
optional int32 port = 2;
}