是时候该了解一波Protocol Buffers了[Android]

前言

Protocol Buffers,是Google公司开发的一种数据描述语言,类似于XML能够将结构化数据序列化,可用于数据存储、通信协议等方面。

它不依赖于语言和平台并且可扩展性极强。现阶段官方支持C++JAVAPython三种编程语言,但可以找到大量的几乎涵盖所有语言的第三方拓展包。

google在2008年7月7号将其作为开源项目对外公布

虽然Protocol Buffers很早就被开源出来,被使用的频率并没有JsonXML多,大多数被用于游戏开发协议,RPC和即时通讯.然而这样的数据交换利器比JsonXML的利处多太多了,但更小更快更简单

Android中快速使用Protocol Buffers

我知道光是想要使用Protocol Buffers,光是Android端是不够的,这里我写了对应SpringBoot集成Protocol Buffers是时候该了解一波Protocol Buffers了[Java]

(一)Android 环境下Gradle配置 Protocol Buffers编译环境

Android项目不会添加默认输出,自Protobuf 3.0.0以来,protobuf-lite Android推荐的Protobuf库,您需要将其添加为代码生成插件。这样插件将代码生成到Android指定的目录下

  • setup 1

    你需要添加protobuf lite到你的依赖中

      dependencies {
        // 你需要添加protobuf lite到你的依赖中,而不再是protobuf-java
        compile 'com.google.protobuf:protobuf-lite:3.0.0'
      }
    复制代码
  • setup 2

    配置编译器,编译Gradle插件,文件输出环境

      protobuf {
        protoc {
          // You still need protoc like in the non-Android case
          artifact = 'com.google.protobuf:protoc:3.0.0'
        }
        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.builtins {
              // In most cases you don't need the full Java output
              // if you use the lite output.
              remove java
            }
            task.plugins {
              javalite { }
            }
          }
        }
      }
    复制代码
  • setup 3

指定 proto文件所在文件夹,并不将.proto文件打入在APK中,这个步骤您也可以忽略

    sourceSets {
        main {
            proto {
                srcDir 'src/main/proto'
                include '**/*.proto'
            }
            java {
                srcDir 'src/main/java'
            }
        }
    }
复制代码

(二)Android项目中编写.proto文件,生成java文件

  • setup 1

    Android项目中编写.proto文件了.例如: 新建 Result.proto文件

      package com.hk.protocolbuffer;
      // 关注1:包名
      option java_package = "com.hk.protocolbuffer";
      option java_outer_classname = "Result";
      // 关注2:option选项
      
      // 关注3:消息模型
      message AppResult {
        optional string message = 1;
        required string data = 2;
        optional string version = 3;
        optional string mobile = 5;
        optional int32  code= 6[default = 500];
        optional string email = 7;
      
      }
    复制代码
  • setup 2

    然后重新构建,在项目的build\generated\source\proto\debug\javalite\com\hk\protocolbuffer下能找到生成的文件,收取成果


    注意:

    • 如果文件无法被Andriod studio 识别,请安装Protobuf Support插件
    • com\hk\protocolbuffer 目录是option java_package 指定的包名
    • build\generated目录生成的java文件都是能直接使用和打入到APK中的
    • .proto语法参照: developers.google.com/protocol-bu…

(三)Android项目中Retrofit 配合 Protobuf 使用

  • setup 1

    添加retrofit2 格式转化器依赖,protobuf2protobuf3两个版本的

    • protobuf2:

    compile 'com.squareup.retrofit2:converter-protobuf:2.1.0'

    • protobuf3:

    compile 'com.squareup.retrofit2:converter-protobuf:2.2.0'

  • setup 2

    Retrofit添加Protobuf解析工厂

      Retrofit.Builder builder = new Retrofit.Builder();
         builder.addConverterFactory(new StringConverterFactory())//添加String格式化工厂
             .addConverterFactory (ProtoConverterFactory.create())//添加Proto格式化工厂
             .addConverterFactory(GsonConverterFactory.create(gson));//添加Gson格式化工厂
             ........
    复制代码
  • setup 3

    使用例子:

      //定义接口
     public interface GitHubService {
    
     @Headers({"Content-Type:application/x-protobuf;charset=UTF-8","Accept: application/x-protobuf"})
     @POST()
     Call<Result.AppResult> psotTest(@Url String  url,@Body Result.AppResult
             appResult);
     }
     
     //获取实例
     Retrofit retrofit = new Retrofit.Builder()
         //设置OKHttpClient,如果不设置会提供一个默认的
         .client(new OkHttpClient())
         //设置baseUrl
         .baseUrl("https://api.github.com/")
         //添加Gson转换器
         .addConverterFactory(ProtoConverterFactory.create())
         .build();
     
     GitHubService service = retrofit.create(GitHubService.class);
     
     //异步请求
     service.enqueue(new Callback<Result.AppResult>() {
             @Override
             public void onResponse(Call<Result.AppResult> call, Response<Result.AppResult> response) {
                     .......
             }
     
             @Override
             public void onFailure(Call<Result.AppResult> call, Throwable t) {
                 .......
             }
         });
    复制代码

注意:

结束

相关工具

由于protobuf调试比较头痛的问题,我在网上找到了一些调试工具(欢迎补充):

相关文章

第一篇-网络篇:

第二篇-Retrofit源码解析

第三篇-Android组件化和快速实现MVP

第三篇-是时候该了解一波Protocol Buffers了[Android]

第四篇-是时候该了解一波Protocol Buffers了[Java]

更新中....

关于个人

Github:github.com/chengzichen

CSDN : blog.csdn.net/chengzichen…

个人博客 : chengzichen.github.io/

本人一直都致力于组件化和插件化的研究如果大家有更好的想法可以联系我一起成长
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值