在Android Studio配置google protobuf


1、在project的build.gradle中配置

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
    }
}

 

注意 Gradle版本至少是 2.12 並且Java 7,本例子使用的是2.2.3protobuf-gradle-plugin使用最新的0.8.0版本。

2、在app的build.gradle中配置

...
apply plugin: 'com.google.protobuf'
...
protobuf {
    //這里配置protoc編譯器
    protoc {
        artifact = 'com.google.protobuf:protoc:3.0.0-alpha-3'
    }
    plugins {
        javalite {
            // The codegen for lite comes as a separate artifact
            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
        }
    }
    //這里配置生成目錄,編譯后會在build的目錄下生成對應的java文件
    generateProtoTasks {
        all().each { task ->
            task.plugins {
                javalite {}
            }
        }
    }
}
dependencies {
    ...
    compile 'com.google.protobuf:protobuf-lite:3.0.0'
    ...
}

 

這里配置的是protobuf-lite最新的3.0.0版本,這個官方推薦給Android中使用的版本。

3、創建proto文件

一般情況下在app/main目錄下創建proto目錄,用於放置.proto文件。本例中創建了一個book.proto

 
           
syntax = "proto2";
option java_package = "net.angrycode.bean";
package bean;
message Book {
    required int32 id = 1;
    required string name = 2;
    optional string desc = 3;
}

proto2proto3的語法不大一樣,例如proto3中不需要requiredoptional修飾字段,而proto2是需要的,這里指定了proto2的語法版本。

這里指定了java_package屬性,說明當protoc生成這個java類的包名為net.angrycode.bean

最后使用message定義了一個名為Book的數據結構,或者說通訊協議。Book有3個字段其中idname是必須的,而desc是可選字段。如果必選字段缺失,讀寫時會發生com.google.protobuf.UninitializedMessageException: Message was missing required fields異常。

4、一個簡單實例

在Android Studio中Build菜單選中Make Project或者Reruild Project可以在app/build目錄下生成對應的java文件,例如創建一個Book實例

 
           
BookOuterClass.Book book = BookOuterClass.Book.newBuilder()
  .setId(1)
  .setName("Prime")
  .setDesc("Code Book")
  .build();

 

proto可以往外寫,使用writeTo(OutputStream)方法,可以是本地文件流,也可以是網絡流。這里寫入文件流

void save() {
        File dir = Environment.getExternalStorageDirectory();
        File file = new File(dir, "book");
        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            book.writeTo(outputStream);
            outputStream.close();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }

 

proto是二進制傳輸,故可以讀取文件流,或者網絡流,這里文件模擬,使用parseFrom(byte[])方法。

 

void read() {
        File dir = Environment.getExternalStorageDirectory();
        File file = new File(dir, "book");
        try {
            FileInputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] data = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(data)) != -1) {
                out.write(data, 0, len);
                out.flush();
            }
            BookOuterClass.Book book = BookOuterClass.Book.parseFrom(out.toByteArray());
            out.close();
            textView.setText("name:" + book.getName() + ",desc:" + book.getDesc());
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }

參考鏈接

https://developers.google.com/protocol-buffers/

https://github.com/google/protobuf

https://github.com/google/protobuf-gradle-plugin

微信掃一掃
關注該公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM