LoginSignup
7
5

More than 5 years have passed since last update.

Android Studio で google Protobuf

Last updated at Posted at 2016-12-21

Protobuf gradle plugin を Android Studio に適用する方法について Android Studio で Java 初心者で Groovy なにそれな私が指向錯誤。

以下プロジェクト名を SampleProject として記述。

環境

  • Ubuntu 16.04
  • Android Studio 2.2.2
  • gradle 2.1.4

SampleProject/build.gradle の編集

このファイルでやる事はリポジトリと classpath の追加

buildscript {
  repositories {
    ...
    // mavenCentral を追加
    mavenCentral()
  }

  dependencies {
    ...
    classpath 'com.google.protobuf-gradle-plugin:0.8.0'
  }
}

SampleProject/app/build.gradle の編集

このファイルでの作業は

  • プラグインの apply
  • protobuf プラグインの設定
  • dependencies の変更
apply plugin: 'com.android.application'
//必ず com.android.application の後に apply する
apply plugin: 'com.google.protobuf'

android {
    (snip)
}

// protobuf プラグインの設定
protobuf {
    // protoc の設定
    protoc {
        artifact = "com.google.protobuf:protoc:3.0.0"
    }
    // javalite プラグインを使う
    plugins {
        lite {
            artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
        }
    }
    // タスク関連
    generateProtoTasks {
        all().each { task ->
            task.plugins {
                lite {}
            }
        }
    }
}

dependencies {
    (snip)
    compile 'com.google.protobuf:protobuf-lite:3.0.0'
}

気をつけるべき事は applycom.android.application の後に行うこと。
protobuf {} の部分については GitHub の issue を参考にした。

編集後は Sync Project with Gradle Files をすること。

試しに .proto ファイルを追加してみる

By default, it includes all *.proto files under src/$sourceSetName/proto

とのことなので SampleProject/app/src/main/proto/ 以下に sample.proto を追加。

syntax="proto2";

option java_package = "com.foo.sampleproject";

message Persion {
  required string name = 1;
  required uint32 age = 2;
}

これでビルドを行うと SampleProject/build/generated/source/proto/debug/lite/com/foo/sampleproject に Sample.Java が生成されている。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5