一.添加protobuf-gradle-plugin插件
1.项目根目录build.gradle里添加:
buildscript { repositories { mavenCentral() } dependencies { classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.6' } }
2.Module下build.gradle里添加:
Android插件必须在Protobuf插件之前:
apply plugin: 'com.android.application' // or 'com.android.library' apply plugin: 'com.google.protobuf'
设置proto文件位置(src/main/proto):
android { sourceSets { main { proto { srcDir 'src/main/proto' ... } } } }
自定义Protobuf编译项:
android { protobuf { // Configure the protoc executable protoc { // Download from repositories artifact = 'com.google.protobuf:protoc:3.6.1' // 这里可以手工指定 path = '/usr/local/bin/protoc' } plugins { // Optional: an artifact spec for a protoc plugin, with "grpc" as // the identifier, which can be referred to in the "plugins" // container of the "generateProtoTasks" closure. javalite { artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0" } } generateProtoTasks { all()*.plugins { javalite {} } } } }
加入依赖包:
dependencies { // You need to depend on the lite runtime library, not protobuf-java api 'com.google.protobuf:protobuf-lite:3.0.1'
api "javax.annotation:javax.annotation-api:1.2" //这个依赖是解决注释报错的问题
}
同步.rebuild 至此build/generated/source/proto/目录下生成相对应的XxxOuterClass文件
引用:
1)https://github.com/google/protobuf-gradle-plugin
2)https://search.maven.org/search?q=g:com.google.protobuf
3)https://blog.csdn.net/YongYu_IT/article/details/80430318
注:
引用1)中有句话Android projects: no default output will be added. Since Protobuf 3.0.0, protobuf-lite is the recommended Protobuf library for Android, and you will need to add it as a codegen plugin.大概意思是Android的项目是没有默认的输出类型这个不同于GO,PHP,PYTHON的项目,从Protobuf 3.0.0后,在Android项目中推荐使用protobuf-lite为做为引用库.这一点尤为重要,不然在后面grpc的生成时很容易出错,该库对应的版本号通过引用2)进行查看
二.grpc代码生成
1.在protobuf选项增加相应代码
android { protobuf { // Configure the protoc executable protoc { // Download from repositories artifact = 'com.google.protobuf:protoc:3.6.1' } plugins { // Optional: an artifact spec for a protoc plugin, with "grpc" as // the identifier, which can be referred to in the "plugins" // container of the "generateProtoTasks" closure. javalite { artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0" } grpc { artifact = "io.grpc:protoc-gen-grpc-java:1.14.0" } } generateProtoTasks { all()*.plugins { javalite {} grpc { option 'lite' } } } } }
2.加入依赖包:
api 'io.grpc:grpc-okhttp:1.14.0' api 'io.grpc:grpc-protobuf-lite:1.14.0' api'io.grpc:grpc-stub:1.14.0'
引用:
1)https://github.com/grpc/grpc-java