Android之Protocol Buffers使用

简介

Protocol Buffers是Google提供的一种持久化数据格式的机制,类似JSON、XML等数据格式。目前有3个版本的库,可以在Android中使用,按照支持特性的多少,从小到大依次为:nano、lite、java版本。

集成步骤

1、配置项目gradle

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

2、配置app gradle

// 应用插件
apply plugin: 'com.google.protobuf'

// 配置proto文件路径
android {
    sourceSets {
        main {
            proto {
                srcDir 'src/main/proto'
                include '**/*.proto'
            }
        }
    }
}

protobuf {
    protoc {
        // You still need protoc like in the non-Android case
        artifact = 'com.google.protobuf:protoc:3.7.1' // 配置编译器版本
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {//builtins方法和plugins方法差异不是很理解,先知道怎么用吧
                java {} // 配置编译选项为java版本
            }
        }
    }
}

dependencies {
    compile 'com.google.protobuf:protobuf-java:3.7.0'
}

lite差异:

apply plugin: 'com.google.protobuf'

  protobuf {
      protoc {
          // Download from repositories
          artifact = 'com.google.protobuf:protoc:3.7.1'
      }
      plugins {
          javalite {
              // The codegen for lite comes as a separate artifact
              artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
          }
      }
      generateProtoTasks {
          all().each { task ->
              task.plugins {//builtins方法和plugins方法差异不是很理解,先知道怎么用吧
                  javalite {}
              }
          }
      }
  }

  dependencies {
      compile "com.google.protobuf:protobuf-lite:3.0.1"
  }

nano差异:

apply plugin: 'com.google.protobuf'

  protobuf {
      protoc {
          // Download from repositories
          artifact = 'com.google.protobuf:protoc:3.0.0' //高版本的编译器,好像不支持nano
      }
	  
      generateProtoTasks {
          all().each { task ->
              task.plugins {//builtins方法和plugins方法差异不是很理解,先知道怎么用吧
                  javanano {}
              }
          }
      }
  }

  dependencies {
      compile "com.google.protobuf.nano:protobuf-javanano:3.1.0"
  }

proto文件示例

新建.proto文件

syntax = "proto3";
option java_package = "com.example.proto";
option java_outer_classname = "ContactsProto";

package proto;

message Friend {
    int32 id = 1;
    string name = 2;
    int32 age = 3;
    string phone = 4;

}

小结

  1. proto2和proto3有一点差异要提出来,proto2文件中字段必须要带required、optional、repeated标示符,proto3不需要。
  2. protoc较低版本,如3.0.0版本,生成的java类,不支持set/get,需要通过object.attr方式访问字段。

参考资料

Android开发之——数据优化ProtoBuf
在Android Studio配置google protobuf
Android 接入protobuf-java库

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值