Android Advancement - Protocol Buffer Complete Introduction to a Higher Efficiency and Lightweight Sequencing Scheme for Performance Optimization

outline

Introduction

Previous article Android Advancement - Protocol Buffer Complete Strategy for a Higher Efficiency and Lightweight Sequencing Scheme for Performance Optimization (10) This paper summarizes some basic knowledge of Protobuf and the characteristics and principles of encoding and decoding in the bottom layer of Protobuf. This article summarizes the application of Protobuf. The following is a list of link addresses in the performance optimization series (continuous updates):

I. Procedures for the Use of Protocol Buffer

Using Protocol Buffer is very simple, and there are three main steps under any platform:

  • Create. proto source file
  • Compile. proto source files

Similar to java files, which are ultimately compiled into class bytecode files, Protobuf relies on JDK development environment. Protobuf also relies on its own compilation environment. It can provide protoc.exe in SDK package to compile proto files into files running on the corresponding platform, or it can compile them through IDE plug-in, no matter what. It's essentially the same way. Download protoc-3.8.0-win64 After decompression, you can view the help through the protoc-h command, which requires corresponding instructions to compile, such as using protoc -- java_out=. xxx. proto to compile classes used in Java environment.

  • Use the methods provided in the compiled product

2. Using Protobuf in Android Studio

Android Studio is more convenient to use Protobuf, because Android Studio provides us with the corresponding plug-ins, so that we only need to create. proto source files, without the need to manually perform compilation tasks. Here are some general steps:

1. Introducing protobuf-gradle-plugin Gradle plugin Android Studio project

Introduce protobuf-gradle-plugin under the build.gradle script in the project root directory

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.0'
        //Introduction of protobuf-gradle-plugin Gradle plug-in
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.8'
    }
}

2. build.gradle uses plug-ins and configures them accordingly under Module requiring Protobuf

  • Application of protobuf-gradle-plugin plug-in
  • Configure the protobuf node at the same level as the android node (the protobuf node is provided by the protobuf-gradle-plugin plug-in)
  • Introducing the library dependencies that Google officially provides
apply plugin: 'com.android.application'
//Application of protobuf plug-in
apply plugin: 'com.google.protobuf'
//Configure protobuf plug-in information
protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.0.0'
    }
    plugins {
        javalite {
            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.plugins {
                javalite { }
            }
        }
    }
}
android{
...
}
dependencies {
	...
    implementation 'com.google.protobuf:protobuf-lite:3.0.0'
}

3. Create proto file

After the second and third steps above, you can create a proto directory (that is, under the src/main / directory) in the main set of the project, and then create a source file with the suffix of. proto in the proto directory. The file name can be arbitrarily selected, and has no direct connection with the data structure described in the. proto file.

//Using the version of protobuf
syntax = "proto2";
//Can save
package tutorial2;
//Generate the package name of the class after compilation
option java_package = "com.example.tutorial";
//Generate the class name of the class after compilation
option java_outer_classname = "AddressBookProtos";
//message can be seen as a key word class in Java environment
message Person {
  //required means that a value must be set (not null). The latter one is Field_Number, not the initial value. It will be involved in the calculation of Tag when encoding.
  required string name = 1;
  //Previous required and others can be seen as annotations or modifiers, followed by data types, followed by variable names.
  required int32 id = 2;
  //Optional represents optional
  optional string email = 3;
  //Enumeration class PhoneType compiles into Person's internal enumeration class in Java environment
  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  //Class PhoneNumber compiles into Person's internal class in Java environment
  message PhoneNumber {
    required string number = 1;
    //Setting default values
    optional PhoneType type = 2 [default = HOME];
  }
  //repeated stores duplicated data (such as collections)
  repeated PhoneNumber phones = 4;
}

message AddressBook {
  repeated Person people = 1;
}

After the configuration environment is successful and written, after compiling the project, you will see the source. proto file compiled corresponding Java classes in the xx/build/generated/source/proto/debug/javalite directory:

The internal structure is compared as follows:

4. Serialization and deserialization using protobuf

  • Create objects using a newBuilder-like constructor pattern
  • Serialization operations are implemented by calling the toByteArray method that comes with the object
  • Deserialize operations by calling the parseFrom method that comes with the object
package com.crazymo.protobuf;

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

import com.crazymo.protobuf.bean.JsonTest;
import com.example.tutorial.AddressBookProtos;
import com.google.protobuf.InvalidProtocolBufferException;

public class MainActivity extends AppCompatActivity {
    final static String TAG="CrazyMo_";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testProtobuf();
    }

    void testProtobuf() {
        //Create objects through similar constructor patterns
        AddressBookProtos.Person.PhoneNumber.Builder builder = AddressBookProtos.Person
                .PhoneNumber.newBuilder().setNumber("666");
        AddressBookProtos.Person.Builder person = AddressBookProtos.Person.newBuilder().setName
                ("CrazyMo")
                .setId(1).addPhones(builder);
        AddressBookProtos.Person.PhoneNumber.Builder builder2 = AddressBookProtos.Person
                .PhoneNumber.newBuilder().setNumber("168");
        AddressBookProtos.Person.Builder person2 = AddressBookProtos.Person.newBuilder().setName
                ("cmo")
                .setId(2).addPhones(builder2);
        AddressBookProtos.AddressBook addressBook = AddressBookProtos.AddressBook.newBuilder()
                .addPeople(person).addPeople(person2).build();

        // Serialization operations that convert objects to byte arrays, such as saving them as a file
        long currTime = System.currentTimeMillis();
        byte[] bytes = addressBook.toByteArray();
        Log.e(TAG, "protobuf Serialization time-consuming:" + (System.currentTimeMillis() - currTime));
        Log.e(TAG, "protobuf Serialized data size:" + bytes.length);

        // Deserialization operations, such as reading from files to memory or parsing data returned from servers
        try {
            currTime = System.currentTimeMillis();
            AddressBookProtos.AddressBook addressBook1 = AddressBookProtos.AddressBook.parseFrom
                    (bytes);
            Log.e(TAG, "protobuf Deserialization is time-consuming:" + (System.currentTimeMillis() - currTime));
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        //Json's Analysis under Simple Contrast
        JsonTest.fastJson();
        JsonTest.gson();
    }
}


Source Port

https://blog.csdn.net/mzpmzk/article/details/80824839

https://www.jianshu.com/p/92dbe1ef0054

https://www.jianshu.com/p/2a5aa5ac6cf6

https://www.ibm.com/developerworks/cn/linux/l-cn-gpb/index.html

https://www.jianshu.com/p/3504d4643dba

https://github.com/protocolbuffers/protobuf

https://github.com/protocolbuffers/protobuf/releases/tag/v3.8.0

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

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

Keywords: Android Gradle Google Java

Added by pazzy on Sun, 15 Sep 2019 11:00:34 +0300