Android Stduio中配置和使用Google Protobuf

Google官方Protobuf文档首页:

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

关于Google Protobuf在Android studio中的配置方法,网上说的各种方案都有,本文给出一个相对简单和谷歌官方的配置方案。

配置需要用到为Protobuf制作的一个插件:

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

 

首先在整个根project的build.gradle配置:

mavenCentral()

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

完整的配置:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.0'
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.8'
        
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

 

在app的build.gradle里面,需要配置:

apply plugin: 'com.google.protobuf'

implementation 'com.google.protobuf:protobuf-java:3.6.1'

已经sourceSets:

    sourceSets {
        main {
            java {
                srcDir 'src/main/java'
            }

            proto {
                srcDir 'src/main/proto'
                include '**/*.proto'
            }
        }
    }
}

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

    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
            }
        }
    }
}

完整的App的build.gralde配置文件:

apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'

android {
   ......

    sourceSets {
        main {
            java {
                srcDir 'src/main/java'
            }

            proto {
                srcDir 'src/main/proto'
                include '**/*.proto'
            }
        }
    }
}

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

    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
            }
        }
    }
}

dependencies {
    ......

    implementation 'com.google.protobuf:protobuf-java:3.6.1'
}

此时就可以在与src/main/java同位置的proto目录写协议文件*.proto了。工程结构:

写两个协议文件aclass.proto(代表班级),student.proto(代表学生)。

student.proto:

option java_package = "zhangphil.test";
option java_outer_classname = "StudentProto";

message Student {
    required int32 id = 1;
    optional string name = 2;
    optional int32 age = 3;
    optional int32 score = 4;
}

 

aclass.proto

import "student.proto";

option java_package = "zhangphil.test";
option java_outer_classname = "AClassProto";

message AClass {
    required int32 id = 1;
    optional string name = 2;
    repeated Student student_list = 3;
}

上层Java代码:

package zhangphil.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.protobuf.InvalidProtocolBufferException;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        byte[] bytes = makeByte();
        try {
            AClassProto.AClass aClass = AClassProto.AClass.parseFrom(bytes);
            List<StudentProto.Student> students = aClass.getStudentListList();
            for (StudentProto.Student student : students) {
                System.out.println(student.getId() + "," + student.getName() + "," + student.getAge());
            }
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
    }


    private byte[] makeByte() {
        StudentProto.Student student1 = StudentProto.Student.newBuilder()
                .setName("zhang")
                .setAge(18)
                .setId(1)
                .build();

        StudentProto.Student student2 = StudentProto.Student.newBuilder()
                .setName("phil")
                .setAge(19)
                .setId(2)
                .build();

        AClassProto.AClass aClass = AClassProto.AClass.newBuilder()
                .setId(1)
                .setName("1班")
                .addStudentList(student1)
                .addStudentList(student2)
                .build();

        byte[] bytes = aClass.toByteArray();
        return bytes;
    }
}

完成后重新rebuild工程项目。就生成对象的协议类了。

运行输出:

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值