preface

  • Used toJson, XML,Data storage format, most of you have never heard of itProtocol Buffer
  • Protocol BufferIs actuallyGoogleProduct of a lightweight & efficient structured data storage format, performance ratioJson, XML,Really strong! Too! Many!

Thanks to Google, I believe the Protocol Buffer has enough traction

  • Today, I’ll go into detailsProtocol BufferinAndroidSpecific use of the platform

Check out Google’s Protocol Buffer before you read this article. Don’t just use Json and XML


directory


Definition 1.

A data storage format for structured data (similar to XML, Json)

  1. GoogleProduction (open source)
  2. Protocol BufferThere are currently two versions:proto2proto3
  3. becauseproto3It’s still in beta, so this isproto2

2. The role

Through serialization (serialization) of structured data, the function of data storage/RPC data exchange is realized

  1. Serialization: The process of converting data structures or objects into binary strings
  2. Deserialization: The process of converting binary strings generated during serialization into data structures or objects

Characteristics of 3.

  • Contrast with the usualXML, Json,Data storage format,Protocol BufferIt has the following characteristics:


4. Application scenarios

Large amount of data transferred & data storage and RPC data exchange requirement scenarios with unstable network environment

Such as instant IM (QQ, wechat) demand scenarios


conclusion

Protocol Buffer is smaller, faster, and easier to use and maintain than XML or Json in scenarios where large amounts of data are transferred.


5. Use a process

  • useProtocol BufferThe process is as follows:

  • Today I’m going to talk aboutProtocol BufferinAndroidSpecific use of the platform


6. Application Instance (Android platform)

  • The specific steps are as follows:

Step 1: Put the generated code files into the project

  • forAndroid (Java) platform, about to compile.protoFile generatedJavaPackage files are copied to the entireAndroidIn the project
  • Placement path:App/SRC/main/JavaIn the folder

Step 2: InGradleaddProtocol BufferVersion depends on

compile 'com. Google. Protobuf: protobuf - Java: 2.6.1'// Note: The protobuf-Java version must be the same as the version where the ProtoCoBuffer was installedCopy the code

Step 3: Specific use in Android projects

3.1 Introduction to message Object classes

Java source code for.proto file conversion = Protocol Buffer class + Message object class (including Builder inner class)

The message object class is an inner class of the Protocol Buffer class

Since the message object class and its inner Builder class are the most commonly used methods & member variables, this section focuses on both.

3.1.1 Message Object Classes (MessageClass)
  • Message object classes Classes write and read message types through binary arrays
  • Methods of use include:
< - way 1: direct serialization and deserialization message - > protocolBuffer. ToByteArray (); Protocolbuffer.parsefrom (byte[] data); // Serialize the message and return a byte array protocolBuffer.parsefrom (byte[] data); // Deserialize (parse) messages from a byte array <-- Method 2: Serialize and deserialize messages over input/output streams (e.g. network output streams) --> protocolBuffer.writeTo(OutputStream output); output.toByteArray(); // Writes a message to the output stream, and then serializes the message ProtocolBuffer.parsefrom (InputStream Input); // Read and deserialize (parse) messages from an input stream // only getters method containing fields // Required String name = 1; public boolean hasName(); // Returns if the field is settruepublic java.lang.String getName(); // required int32 id = 2; public boolean hasId(); public int getId(); // optional string email = 3; public boolean hasEmail(); public String getEmail(); // repeated .tutorial.Person.PhoneNumber phone = 4; Public List<PhoneNumber> getPhoneList(); public int getPhoneCount(); Get and set the getters and setters for a particular element of the list by indexCopy the code

Commonly used above, see the official documentation for more

3.1.2 Builderclass

Creates a message constructor & sets/gets the field value of a message object & creates a message class instance

An inner class that belongs to the message object class

A. Create a message constructor

Demo.Person.Builder person = Person.newBuilder();
Copy the code

B. Set/obtain the field value of the message object as follows:

// Standard JavaBeans style: including getters and setters // Required string name = 1; public boolean hasName(); // Returns if the field is settrue
public java.lang.String getName();
public Builder setName(String value); public Builder clearName(); // Set the field back to its empty state // Required int32 id = 2; public boolean hasId(); public int getId(); public BuildersetId(int value);
public Builder clearId();

// optional string email = 3;
public boolean hasEmail();
public String getEmail();
public Builder setEmail(String value); public Builder clearEmail(); // repeated .tutorial.Person.PhoneNumber phone = 4; Public List<PhoneNumber> getPhoneList(); public int getPhoneCount(); Getters and setters public PhoneNumber getPhone(int index); public BuildersetPhone(int index, PhoneNumber value); public Builder addPhone(PhoneNumber value); Public Builder addAllPhone(Iterable<PhoneNumber> value); // Add a container full of elements to the list public Builder clearPhone(); Public Builder isInitialized() // Check whether all required fields have been set public Builder toString() : Public Builder mergeFrom(Message Other) public Builder mergeFrom(Message other) public Builder mergeFrom(Message other) public Builder mergeFrom(Message other) Public Builder clear() // Clear all elements to empty state.Copy the code

3.2 Usage

  • The usage steps are as follows: ** Step 1: ** Constructs the message constructor through the inner class Builder class of the message class ** Step 2: ** sets the value of the message field through the message constructor ** Step 3: ** creates the message class object through the message constructor ** Step 4: ** serializes/deserializes the message

  • The details are as follows :(the comments are very clear)

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); Demo.person.builder personBuilder = demo.person.newBuilder (); // Step 2: Set the field you want to set to the value of your choice personBuilder.setName("Carson"); // When defining the.proto file, the field modifier for this field is required, so personBuilder.setid (123) must be assigned; // When defining the.proto file, the field modifier for this field is required, so personBuilder.setemail ("[email protected]"); / / in the definition. Proto file, the field of the modifier is optional, so can't assignment/assignment (not assignment will use the default value) Demo. Person. PhoneNumber. Builder PhoneNumber = Demo.Person.PhoneNumber.newBuilder(); phoneNumber.setType( Demo.Person.PhoneType.HOME); PhoneNumber. SetNumber (phoneNumber."0157-23443276"); // PhoneNumber message is nested in the Person message, which can be read as an internal class // so create the object through the external class // Step 3: create the message object demo. Person Person = through the message constructor personBuilder.build(); // Step 4: Serialize and deserialize messages (two ways) /* Method 1: Serialize and deserialize messages directly */ // a Serialize byte[] byteArray1 = Person.tobytearray (); System.out.println(Arrays.toString(byteArray1)); // Serialize the Person message class object to byte[] bytes system.out.println (Arrays.toString(byteArray1)); Demo.person person_Request = demo.person.parsefrom (byteArray1); // When received the byte array byte[] deserializes into the Person message class object System.out.println(person_request.getName ()); System.out.println(person_Request.getId()); System.out.println(person_Request.getEmail()); } catch (IOException e) {e.printStackTrace(); } /* Approach 2: serialize and deserialize messages over input/output streams (such as network output streams) */ // a. Serialize ByteArrayOutputStream output = new ByteArrayOutputStream(); try { person.writeTo(output); // Serialize the message and write it to the output stream (here ByteArrayOutputStream is used instead)} catch (IOException e) {e.printStackTrace(); } byte[] byteArray = output.toByteArray(); // b. Deserialize ByteArrayInputStream input = new ByteArrayInputStream(byteArray); Try {demo.person person_Request = demo.person.parsefrom (input); // Deserialize the message system.out.println (person_request.getName ()) from the input stream; System.out.println(person_Request.getId()); System.out.println(person_Request.getEmail()); } catch (IOException e) {e.printStackTrace(); }}}Copy the code

The Demo address

Carson_Ho’s Github: github.com/Carson-Ho/P…

Advanced features

  • Thoughtful Google also provides a way toProtocol BuffEncoding mode to other encoding mode, such asJson,XML, etc.

Convert a Protocol Buff object to another encoded datastore object

  • What is shown below is the followingProtocol BuffObject converted toJsonobject
// Step 1: Compile dependencies in Gradle'com. Googlecode. Protobuf - Java - format: protobuf - Java - format: 1.4'// Step 2: serialize the 'Protocol Buff' object to the 'Json' object JsonFormat JsonFormat = new JsonFormat(); String person2json = jsonFormat.printToString(mProtoBuffer);Copy the code

This concludes the use of the Protocol Buffer.


7. To summarize

  • By the end of this article, you should have a pretty good ideaProtocol BufferAndroidUse of the platform
  • aboutProtocol BufferSee:
  1. Check out Google’s Protocol Buffer and don’t just use Json and XML
  2. Install the Protocol Buffer
  3. This is a bona fide explanation of the Protocol Buffer syntax
  4. Why does the Protocol Buffer serialize so well?
  5. Android: Analyze the source code for the Protocol Buffer
  • In the next article I will discussProtocol BufferThe source codeCarry on detailed analysis, have interest can continue to pay attention toCarson_Ho android Development Notes

Thumb up, please! Because your encouragement is the biggest power that I write!


Welcome to follow Carson_ho on wechat