Integration of Proto3 on Android

Keywords: Android Google Java Gradle

Proto 3 and proto 2 are very different. Most of the Internet is about proto 2. Because of the habit of using the latest library, we insist on integrating proto 3

build.gradle configuration under Project directory

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

build.gradle configuration under Module

stay

apply plugin: 'com.android.application' 

perhaps

apply plugin: 'com.android.library'

Lower increase

apply plugin: 'com.google.protobuf'

At the same time, the number of android peers increased

    protoc {
        artifact = 'com.google.protobuf:protoc:3.8.0'
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option "lite"
                }
            }
        }
    }
    //Generated directory
    generatedFilesBaseDir = "$projectDir/src/generated"
}

Add in android

        main {
            java {
                srcDir 'src/main/java'
            }
            proto {
                srcDir 'src/main/proto' //Specify the. proto file path
            }
        }
    }

Finally, add it to dependencies

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.google.protobuf:protobuf-java:3.8.0'
    implementation 'com.google.protobuf:protoc:3.8.0'
}

Add the proto directory of the same level with java under module to define the proto message data body

build project can generate the generated directory which is the same as the main directory. The java classes in the proto directory can be directly used

Other introductions

The difference between proto 3 and proto 2 is as follows: http://www.cppblog.com/sunicdavy/archive/2016/01/25/212739.html
To be continued

Posted by IceHawk on Thu, 19 Mar 2020 11:15:27 -0700