是時候該瞭解一波Protocol Buffers了[Android]

前言

Protocol Buffers,是Google公司開發的一種數據描述語言,相似於XML可以將結構化數據序列化,可用於數據存儲、通訊協議等方面。java

它不依賴於語言和平臺而且可擴展性極強。現階段官方支持C++JAVAPython三種編程語言,但能夠找到大量的幾乎涵蓋全部語言的第三方拓展包。git

google在2008年7月7號將其做爲開源項目對外公佈github

雖然Protocol Buffers很早就被開源出來,被使用的頻率並無JsonXML多,大多數被用於遊戲開發協議,RPC和即時通信.然而這樣的數據交換利器比JsonXML的利處多太多了,但更小更快更簡單編程

Android中快速使用Protocol Buffers

我知道光是想要使用Protocol Buffers,光是Android端是不夠的,這裏我寫了對應SpringBoot集成Protocol Buffers是時候該瞭解一波Protocol Buffers了[Java]api

(一)Android 環境下Gradle配置 Protocol Buffers編譯環境

Android項目不會添加默認輸出,自Protobuf 3.0.0以來,protobuf-lite Android推薦的Protobuf庫,您須要將其添加爲代碼生成插件。這樣插件將代碼生成到Android指定的目錄下網絡

  • setup 1app

    你須要添加protobuf lite到你的依賴中異步

    dependencies {
        // 你須要添加protobuf lite到你的依賴中,而再也不是protobuf-java
        compile 'com.google.protobuf:protobuf-lite:3.0.0'
      }
    複製代碼
  • setup 2maven

    配置編譯器,編譯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/

本人一直都致力於組件化和插件化的研究若是你們有更好的想法能夠聯繫我一塊兒成長
圖片名稱
相關文章
相關標籤/搜索