如何在Android使用Protobuf

    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();
        }

    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

景兄弟1366

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值