preface

Protocol BuffersIs a data description language developed by Google. Similar to XML, it can serialize structured data and be used for data storage and communication protocols.

It is language – and platform-independent and highly extensible. Official support at this stageC++,JAVA,PythonThree programming languages, but a large number of third-party extensions can be found covering almost all languages.

Google announced it as an open source project on July 7, 2008

Although Protocol Buffers have long been open-source, they are used less often than Json and XML, mostly for game development protocols,RPC and instant messaging. However, such data exchange tools have many more advantages than Json and XML, but are smaller, faster, and simpler

Quick use of Protocol Buffers in Android

I know that it is not enough to use Protocol Buffers on the Android side alone, so HERE I write the corresponding SpringBoot integrated Protocol BuffersIt’s time to learn about a Protocol Buffers [Java]

Gradle configures Protocol Buffers in an Android environment

Android projects don’t add default output, Protobuf-Lite is the Recommended Protobuf library for Android since Protobuf 3.0.0, you need to add it as a code generation plug-in. This will generate the code to the directory specified by Android

  • setup 1

    You need to add Protobuf Lite to your dependencies

    Dependencies {/ / you need to add the protobuf lite to rely on you, rather than the protobuf - Java compile 'com. Google. Protobuf: protobuf - lite: 3.0.0'}Copy the code
  • setup 2

    Configure the compiler, compile the Gradle plug-in, file output environment

    Protobuf {protoc {/ / You still need protoc like in the non - Android case an 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 {/ / will  cases you don't need the full Java output // if you use the lite output. remove java } task.plugins { javalite { } } } }}Copy the code
  • setup 3

Specify the folder where the proto file is located and do not put the. Proto file into APK, which you can also ignore

    sourceSets {
        main {
            proto {
                srcDir 'src/main/proto'
                include '**/*.proto'
            }
            java {
                srcDir 'src/main/java'
            }
        }
    }
Copy the code

(two)Android project preparation. Proto file, Java file generation

  • setup 1

    Android project to write.proto file. For example, create result. proto

    package com.hk.protocolbuffer; // Note 1: package name option java_package = "com.hk.protocolBuffer "; option java_outer_classname = "Result"; 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; }Copy the code
  • setup 2

    Then rebuild, in the project build\generated\source\proto\debug\javalite\com\hk\ protocolBuffer can find the generated file, receive results


    Note:

    • If the file is not recognized by Android Studio, install itProtobuf SupportThe plug-in
    • com\hk\protocolbufferDirectory isoption java_packageSpecifies the package name
    • build\generatedThe directory generates Java files that can be used and plugged directly into APK
    • Proto grammar reference: developers.google.com/protocol-bu…

(III) Retrofit is used in conjunction with Protobuf in Android projects

  • setup 1

    Added retroFIT2 format converter dependencies, available in both Protobuf2 and Protobuf3 versions

    • Protobuf2:

    The compile 'com. Squareup. Retrofit2: converter - protobuf: 2.1.0'

    • Protobuf3:

    The compile 'com. Squareup. Retrofit2: converter - protobuf: 2.2.0'

  • setup 2

    Retrofit adds a Protobuf parsing factory

    Retrofit.Builder builder = new Retrofit.Builder(); Builder. AddConverterFactory (new StringConverterFactory ()) / / add the String format chemical plant. The addConverterFactory (ProtoConverterFactory. The create ()) / / add the format of Proto chemical plant. AddConverterFactory (GsonConverterFactory. Create (gson)); // Add Gson format chemical plant........Copy the code
  • setup 3

    Use examples:

    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 = new retrofit.builder () // Set OKHttpClient, if not set will provide a default.client(new OKHttpClient ()) . / / set the baseUrl baseUrl (" https://api.github.com/ ") / / add Gson converter addConverterFactory (ProtoConverterFactory. The create ()) .build(); GitHubService service = retrofit.create(GitHubService.class); 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) { ....... }});Copy the code

Note:

  • proto2andproto3It’s different,converterThe reflection method is used to retrieve the field, so you need to use the corresponding version
  • ProtoConverterFactoryWhenever possible, configure it in front of the Gson parser
  • If you’re not sure how Retrofit works, please refer to the following details you should know: Understand Retrofit for better use and Android Web requests Retrofit+ OKHTTP +Rxjava
  • You can also use the ComponentPlugin to quickly build Componentization and MVP(ComponentPlugin focuses on :Android componentization and Fast implementation of MVP(dry))

The end of the

Related tools

Because protobuf debugging is a headache, I found some debugging tools online (welcome to add):

  • Tools: github.com/zhanjindong…
  • Baidu open source github.com/jhunters/jp…

Related articles

The first – Network:

  • [starting from scratch series]AndroidApp development road (a) network request encapsulation (a)

Retrofit source code analysis

  • AndroidApp development road (2)Retrofit principle part

Article 3 -Android componentization and Fast MVP Implementation

  • ComponentPlugin focuses on :Android componentization and rapid implementation of MVP(Dry)

It’s time to learn about a Protocol Buffers [Android]

  • It’s time to learn about a Protocol Buffers [Android]

It’s time to learn about a Protocol Buffers wave [Java]

  • It’s time to learn about a Protocol Buffers [Java]

Update in the…

About personal

Github:github.com/chengzichen

CSDN: blog.csdn.net/chengzichen…

Personal blog: chengzichen.github. IO /

I have been committed to the research of componentization and plug-in. If you have better ideas, please contact me to grow up together