protobuf是一种占用空间小,解析速度快的数据通信协议,相对xml和json而言,更适合网络传输。但传输是二进制,生成的文件可读性差,不过也相对安全,因为不配合对应的类格式,是不知道内容的。
下面讲一下如何在Android使用protobuf:
首先是根目录下的build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
mavenCentral()//配置Protobuf需要
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.3'
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.13'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
然后是app下的build,.gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'
android {
compileSdkVersion 29
buildToolsVersion "30.0.1"
defaultConfig {
applicationId "com.example.androidinterviewjxd"
minSdkVersion 23
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
java {
srcDir 'src/main/java'
}
proto {
srcDir 'src/main/proto'
include '**/*.proto'
}
}
}
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.6.1'
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
}
task.builtins {
java {}
}
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.protobuf:protobuf-java:3.11.0'
}
然后在src/main/proto下新建student.proto:
option java_package = "com.example.androidinterviewjxd";
option java_outer_classname = "StudentProto";
message Student {
required int32 id = 1;
optional string name = 2;
optional int32 age = 3;
optional int32 score = 4;
}
最后在Activity中实现protobuf的创建和读取:
package com.example.androidinterviewjxd.protobuf;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.example.androidinterviewjxd.R;
import com.example.androidinterviewjxd.StudentProto;
import com.example.androidinterviewjxd.utils.FileUtils;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.File;
import java.io.IOException;
public class ProtoBufTestActivity extends AppCompatActivity {
public static final String TAG = "ProtoBufTestActivity_tag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proto_buf_test);
StudentProto.Student student1 = StudentProto.Student.newBuilder()
.setName("jxd")
.setAge(28)
.setId(111)
.build();
byte[] bytes = student1.toByteArray();
File stuFile = new File(getCacheDir().getParent()+File.separator+"stuproto.proto");
try{
if(!stuFile.exists()){
stuFile.createNewFile();
}
}catch (IOException e){
e.printStackTrace();
}
FileUtils.writeByteArrToFile(stuFile.getAbsolutePath(),bytes);
try {
StudentProto.Student student2 = StudentProto.Student.parseFrom(bytes);
Log.d(TAG,student2.getId() + "," + student2.getName() + "," + student2.getAge());
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
}