ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-06-30 17:02:24  阅读:170  来源: 互联网

标签:google java Protobuf androidx gradle 安卓中 序列化 com 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;
    }

标签:google,java,Protobuf,androidx,gradle,安卓中,序列化,com,protobuf
来源: https://blog.csdn.net/y645633369/article/details/118365033

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有