配置Gradle
1、项目的build.gradle文件加入:
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
如果使用的是Build Gradle3.0
及以上的版本,会和protobuf-gradle-plugin
插件有冲突,将protobuf-gradle-plugin
升级到0.8.2
版本。
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.2'
![](https://img.haomeiwen.com/i2226455/4c7148a947cd8663.png)
2、模块的build.gradle
- 顶部添加protobuf插件
apply plugin: 'com.google.protobuf'
- android结点增加proto文件位置配置
sourceSets {
main {
proto {
srcDir 'src/main/proto'
include '**/*.proto'
}
java {
srcDir 'src/main/java'
}
}
}
- 添加依赖
implementation 'com.google.protobuf:protobuf-lite:3.0.0'
- 增加protobuf结点
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.1.0'
}
plugins {
javalite {
// The codegen for lite comes as a separate artifact
artifact = 'com.google.protobuf:protoc-gen-javalite:3.1.0'
}
}
generateProtoTasks {
all().each { task ->
task.plugins {
javalite {}
}
}
}
generatedFilesBaseDir = "$projectDir/src/generated"
}
目录结构
![](https://img.haomeiwen.com/i2226455/960deb071af21c3f.png)
附
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.ydtf.nbmobile.protobufdemo4"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
proto {
srcDir 'src/main/proto'
include '**/*.proto'
}
java {
srcDir 'src/main/java'
}
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.1'
testCompile 'junit:junit:4.12'
implementation 'com.google.protobuf:protobuf-lite:3.0.0'
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.1.0'
}
plugins {
javalite {
// The codegen for lite comes as a separate artifact
artifact = 'com.google.protobuf:protoc-gen-javalite:3.1.0'
}
}
generateProtoTasks {
all().each { task ->
task.plugins {
javalite {}
}
}
}
generatedFilesBaseDir = "$projectDir/src/generated"
}
Gradle3语法变动
gradle3中compile
和testCompile
变成implementation
和testImplementation
。
参考:
在Android Studio配置google protobuf
Android Studio3.0之后gradle.build中dependencie依赖由compile变为implementation
网友评论