1、在项目build.gradle 中添加protobuf gradle plugin
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
//添加protobuf plugin
classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.8"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
2、app build 中配置:
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf' //在gradle脚本开始处声明依赖的插件
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.smartisanos.giant.assistantservice"
minSdkVersion 28
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
signingConfigs {
debug {
try {
storeFile file("../plat.keystore")
storePassword '123456'
keyAlias 'platform'
keyPassword '123456'
} catch (ex) {
throw new InvalidUserDataException("You should define KEYSTORE_PASSWORD and KEY_PASSWORD in gradle.properties.")
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
//编写编译任务,调用plugin编译生成java文件
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.0.0'//编译器版本
}
plugins {
javalite {
artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'//指定当前工程使用的protobuf版本为javalite版,以生成javalite版的java类
}
}
generateProtoTasks.generatedFilesBaseDir = "$projectDir/src/main/java" //指定编译生成java类的存放位置
generateProtoTasks {
all().each { task ->
task.plugins {
javalite {
outputSubDir = '' //指定存放位置的二级目录,这里未指定
}
}
}
}
}
//指定原始.proto文件的位置
android {
sourceSets {
main {
java {
srcDirs 'src/main/java'
}
proto {
srcDirs 'src/main/proto'
}
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.protobuf:protobuf-lite:3.0.0' //依赖protobuf-lite库
}
3.proto 文件示例
package proto;
option java_package = "com.smartisanos.giant.assistantservice.discover";
option java_outer_classname = "DiscoveryMessageProto";
message DiscoveryMessage {
string ip = 1; //这里不是赋值,是编号,相当于tag
string clientName = 2;
string type = 3;
string version = 4;
}
写完.proto 文件,需要先编译下项目以便生成可供序列化和反序列的java类,序列化用法:
DiscoveryMessageProto.DiscoveryMessage discoveryMessage = DiscoveryMessageProto.DiscoveryMessage.newBuilder().setIp(szLocalIp)
.setType(ConnTeckConstant.MSGTYPE_SEARCH_TV_REQUEST).setVersion("1.0").build();
反序列化:
try {
discoveryMessage = DiscoveryMessageProto.DiscoveryMessage.parseFrom(packet.getData());
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
Log.v("proto"," invalid protocol buffer exception: " + Log.getStackTraceString(e));
}
问题:
Configuration with name 'debugAndroidTestCompile' not found.
解决:
更新protobuf的版本号到最新的,需要根据gradle的版本进行配置,可以到github上查看最新版本<u>Protobuf Plugin for Gradle</u>
网友评论