proto3和proto2有很大区别,网上大多是proto2的介绍,因为有使用最新库的习惯,所以坚持集成proto3
一、Project目录下build.gradle配置
buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.10'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
二、Module下build.gradle配置
在
apply plugin: 'com.android.application'
或者
apply plugin: 'com.android.library'
下增加
apply plugin: 'com.google.protobuf'
同时,在android同级增加
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.8.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option "lite"
}
}
}
}
//生成目录
generatedFilesBaseDir = "$projectDir/src/generated"
}
在android里增加
sourceSets {
main {
java {
srcDir 'src/main/java'
}
proto {
srcDir 'src/main/proto' //指定.proto文件路径
}
}
}
最后在depends里增加
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.protobuf:protobuf-java:3.8.0'
implementation 'com.google.protobuf:protoc:3.8.0'
}
完整的module下build.gradle文件如下:
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.8.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option "lite"
}
}
}
}
//生成目录
generatedFilesBaseDir = "$projectDir/src/generated"
}
android {
compileSdkVersion 28
defaultConfig {
applicationId "cn.starcart.testjni"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
sourceSets {
main {
java {
srcDir 'src/main/java'
}
proto {
srcDir 'src/main/proto' //指定.proto文件路径
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
version "3.10.2"
}
}
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
implementation 'com.google.protobuf:protobuf-java:3.8.0'
}
三、module下增加与java同级目录proto目录,用于定义proto消息数据体
如上图中user定义如下:
syntax = "proto3";
package cn.proto.java.bean; //输出的包名
option java_outer_classname = "UserBean"; //输出的类名
message User{
int64 id = 1 ;
string name = 2 ;
}
build project即可生成与main同级目录generated目录,该目录下生成proto目录下的java类,可直接使用了
proto使用上也比较简单,参考官方文档即可
四、其他介绍
proto3语法定义:https://developers.google.com/protocol-buffers/docs/proto3
proto3和proto2的区别参考:http://www.cppblog.com/sunicdavy/archive/2016/01/25/212739.html