1. Kotlin
引入 protobuf
buildscript {
repositories {
gradlePluginPortal ( )
}
dependencies {
classpath 'com. google. protobuf: protobuf- gradle- plugin: 0.8 . 19 '
}
}
plugins {
id 'com. android. application' version '7.2 . 1 ' apply false
id 'com. android. library' version '7.2 . 1 ' apply false
id 'org. jetbrains. kotlin. android' version '1.6 . 10 ' apply false
id 'com. google. protobuf' version '0.8 . 18 ' apply false
}
task clean ( type: Delete) {
delete rootProject. buildDir
}
plugins {
id 'com. android. application'
id 'org. jetbrains. kotlin. android'
id 'com. google. protobuf'
}
android {
compileSdk 32
sourceSets {
main {
java {
srcDirs += 'build/ generated/ source/ proto/ main/ java'
}
kotlin {
srcDirs += 'build/ generated/ source/ proto/ main/ kotlin'
}
proto {
srcDir 'src/ main/ java/ com/ example/ gatttestapp/ protobuf'
}
}
}
defaultConfig {
applicationId "com.example.gatttestapp"
minSdk 21
targetSdk 32
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
}
kotlinOptions {
jvmTarget = '1.8 '
}
}
dependencies {
implementation 'androidx. core: core- ktx: 1.8 . 0 '
implementation 'androidx. appcompat: appcompat: 1.5 . 0 '
implementation 'com. google. android. material: material: 1.6 . 1 '
implementation 'androidx. constraintlayout: constraintlayout: 2.1 . 4 '
implementation 'com. google. protobuf: protobuf- javalite: 3.20 . 1 '
implementation ( "androidx.work:work-runtime:2.7.1" )
testImplementation 'junit: junit: 4.13 . 2 '
androidTestImplementation 'androidx. test. ext: junit: 1.1 . 3 '
androidTestImplementation 'androidx. test. espresso: espresso- core: 3.4 . 0 '
}
protobuf {
protoc {
artifact = 'com. google. protobuf: protoc: 3.8 . 0 '
}
generateProtoTasks {
all ( ) . each {
task ->
task. builtins {
java {
option "lite"
}
}
}
}
}
简单使用
syntax = "proto3" ;
package proto;
option java_package = "com.example.demo" ;
option java_outer_classname = "PersonProto" ;
message Person {
string name = 1 ;
string id= 2 ;
repeated Card cList = 6 ;
}
var person = personProto. Person . newBuilder ( ) . setName ( "123" ) . setId ( "456" ) . build ( )
val person2: personProto. Person = personProto. Person. parseFrom ( person. toByteArray ( ) )
Log. e ( TAG, "id : ${
person2. id } , name: ${
person2. name } " )
var dataTemp = personProto. Person. parseFrom ( person . toByteArray ( ) )
Log. e ( TAG, "dataTemp : ${
dataTemp. toString ( ) } " )