1. 程式人生 > >利用Android Studio將Protobuf檔案生成Java檔案

利用Android Studio將Protobuf檔案生成Java檔案

配置Gradle

1、專案的build.gradle檔案加入:

 classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'

專案級

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' } } }
  • 新增依賴
    compile 'com.google.protobuf:protobuf-java:3.1.0'
    compile 'com.google.protobuf:protoc:3.1.0'
  • 增加protobuf結點
protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.1.0'
} generateProtoTasks { all().each { task -> task.builtins { remove java } task.builtins { java {} // Add cpp output without any option. // DO NOT omit the braces if you want this builtin to be added.
cpp {} } } } generatedFilesBaseDir = "$projectDir/src/generated" }

目錄結構

目錄結構

完整的模組的build.gradle

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'
    compile 'com.google.protobuf:protobuf-java:3.1.0'
    compile 'com.google.protobuf:protoc:3.1.0'
    testCompile 'junit:junit:4.12'
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.1.0'
    }

    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
                // Add cpp output without any option.
                // DO NOT omit the braces if you want this builtin to be added.
                cpp {}
            }
        }
    }

    generatedFilesBaseDir = "$projectDir/src/generated"
}