Protobuf在安卓中的简单使用之序列化与反序列化

Protobuf简单使用笔记

本次使用的环境信息:

gradle: 6.5
ide: android studio 4.1.3

1.引入Protobuf编译插件

在项目根目录(build.gradle)中引入protobuf-gradle-plugin插件

classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.16'

完整文件:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.3"
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.16'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

注意:
这里引入的版本这里有一个坑,刚开始接触时,网上说的都是引入0.8.2或其他低版本,我第一次引入后编译是没有问题的,但是当我进行的第二步(就是下一步)时,提示了一个一次,

Unable to find method 'org.gradle.api.internal.file.DefaultSourceDirectorySet.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/gradle/api/internal/file/FileResolver;Lorg/gradle/api/internal/file/collections/DirectoryFileTreeFactory;)V'
org.gradle.api.internal.file.DefaultSourceDirectorySet.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/gradle/api/internal/file/FileResolver;Lorg/gradle/api/internal/file/collections/DirectoryFileTreeFactory;)V

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

Re-download dependencies and sync project (requires network)
The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.

Stop Gradle build processes (requires restart)
Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

尝试了各种版本后发现是这里引入的版本问题,应该是低版本插件与我的gradle环境不匹配导致的,当发现这个问题时自己去更改下版本试试,下方是插件仓库连接,拿走不谢

https://mvnrepository.com/artifact/com.google.protobuf/protobuf-gradle-plugin

2.声明插件

在app模块的gradle配置文件(app/build.gradle)中声明插件

apply plugin: 'com.android.application'

完整文件:

plugins {
    id 'com.android.application'
    id 'com.google.protobuf'  //这个是本次要新加入的代码
}
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.fs.protobufdemo"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }


}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

以前声明都是apply plugin: 'com.android.application'这种的,可能是更新了,现在改写法了,都一样的东西.不影响

3.配置protobuf编译器

在app模块的gradle配置文件(app/build.gradle)中加入下方代码

protobuf {
    //配置protoc编译器
    protoc {
        artifact = 'com.google.protobuf:protoc:3.17.3'
    }
    //这里配置生成目录,编译后会在build的目录下生成对应的java文件
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
            }
        }
    }
}

完整文件:

plugins {
    id 'com.android.application'
    id 'com.google.protobuf'
}
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.fs.protobufdemo"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }


}

protobuf {
    //配置protoc编译器
    protoc {
        artifact = 'com.google.protobuf:protoc:3.17.3'
    }
    //这里配置生成目录,编译后会在build的目录下生成对应的java文件
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
            }
        }
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

4.设置源码目录

在app模块的gradle配置文件(app/build.gradle)中加入下方代码

    sourceSets {
        main {
            java {
                srcDir 'src/main/java'
            }
            proto {
                srcDir 'src/main/proto'
            }
        }
    }

完整文件:

plugins {
    id 'com.android.application'
    id 'com.google.protobuf'
}
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.fs.protobufdemo"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    sourceSets {
        main {
            java {
                srcDir 'src/main/java'
            }
            proto {
                srcDir 'src/main/proto'
            }
        }
    }

}
protobuf {
    //配置protoc编译器
    protoc {
        artifact = 'com.google.protobuf:protoc:3.17.3'
    }
    //这里配置生成目录,编译后会在build的目录下生成对应的java文件
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
            }
        }
    }
}


dependencies {

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.protobuf:protobuf-java:3.17.3'
    implementation 'com.google.protobuf:protoc:3.17.3'
}

5.引入依赖

在app模块的gradle配置文件(app/build.gradle)中加入下方代码

    implementation 'com.google.protobuf:protobuf-java:3.17.3'
    implementation 'com.google.protobuf:protoc:3.17.3'

完整文件:

plugins {
    id 'com.android.application'
    id 'com.google.protobuf'
}
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.fs.protobufdemo"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }


}

protobuf {
    //配置protoc编译器
    protoc {
        artifact = 'com.google.protobuf:protoc:3.17.3'
    }
    //这里配置生成目录,编译后会在build的目录下生成对应的java文件
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.builtins {
                java {}
            }
        }
    }
}


dependencies {

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.protobuf:protobuf-java:3.17.3'
    implementation 'com.google.protobuf:protoc:3.17.3'
}

6.同步项目

我是在上方每一步完成都同步一次,只要到这一步as还没有报错,所有配置工作现在已经完成了

7.在as中安装protobuf插件

直接去file->setting ->plugins中搜索protobuf 找到全文匹配的那个(一般都是第一个)安装好后重启就好了

8.编写proto文件

在app/main/proto/目录下(没有就proto目录就自己创建一个,)新建Book.proto文件并编写内容

syntax = "proto3";
package com.fs.protobufdemo;

message Book {
    string name = 1;
    string author = 2;
    int32 pages =3;
}

9.生成Java文件

到这一步编译后就会在app/build/generated/source/proto/debug/java/包名/目录下面生成一个java文件,这个文件就是用来序列化与反序列化的文件,如果与后端对接的话就可以直接把此文件给到后端的小伙伴直接使用,自己在这个项目中不需要移动此文件(这个文件是根据Book.proto文件编译出来的,Book.proto文件改变的话他也会改变)就可以直接使用了.

10.初始化数据类对象关键代码

在序列化操作之前需要先有此数据类的对象

                BookOuterClass.Book.Builder builder = BookOuterClass.Book.newBuilder();
                BookOuterClass.Book book = builder.setAuthor("张三").setName("无敌风火轮").setPages(500).build();

11.序列化操作关键代码

    private byte[] bookSerialize(BookOuterClass.Book book) {
        byte[] bytes = new byte[book.getSerializedSize()];
        CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(bytes);
        try {
            book.writeTo(codedOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

12.反序列化操作关键代码

    private BookOuterClass.Book bookDeserialization(byte[] data) {
        BookOuterClass.Book book = null;
        try {
            book = BookOuterClass.Book.parseFrom(data);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        return book;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值