问题描述
我正在尝试在 Android 移动应用上开发 GRPC。我从 https://github.com/grpc/grpc-java/tree/v1.34.1/examples/android/helloworld
找到了 HelloWorld 示例项目当我构建项目时,出现以下错误:
导入 io.grpc.examples.helloworld.GreeterGrpc; ^ 符号:类 GreeterGrpc 位置:包 io.grpc.examples.helloworld
我正在尝试使用该 gradle 构建应用程序:
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'
android {
compileSdkVersion 28
defaultConfig {
applicationId "io.grpc.helloworldexample"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
buildTypes {
debug { minifyEnabled false }
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
}
}
lintOptions {
disable 'GoogleAppIndexingWarning','HardcodedText','InvalidPackage'
textReport true
textoutput "stdout"
}
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.2.0"
}
plugins {
lite {
artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
}
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
}
task.plugins {
lite { }
}
}
}
}
dependencies {
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.google.android.material:material:1.1.0-alpha09'
implementation 'io.grpc:grpc-okhttp:1.34.1'
implementation 'io.grpc:grpc-protobuf-lite:1.34.1'
implementation 'io.grpc:grpc-stub:1.34.1'
compileOnly 'org.apache.tomcat:annotations-api:6.0.53' // necessary for Java 9+
}
像这样的 proto 文件:
Syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service deFinition.
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
解决方法
该错误表明您缺少生成的 GreeterGrpc 服务代码。您需要向 protoc
编译器提供 gRPC-Java 代码生成插件才能获取生成的 gRPC 代码。
protobuf {
protoc { artifact = "com.google.protobuf:protoc:3.12.0" }
plugins {
grpc { artifact = "io.grpc:protoc-gen-grpc-java:1.34.1" }
}
generateProtoTasks {
all().each { task ->
task.builtins {
java { option 'lite' }
}
task.plugins {
grpc { // Options added to --grpc_out
option 'lite' }
}
}
}
}
请注意,在这种情况下,我已更改为使用 protoc
v3.12.0。如果您使用的 protoc
早于 v3.8.0,则
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.2.0"
}
plugins {
lite {
artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
}
grpc {
// some old grpc version,newer ones may not work,suggest upgrading
artifact = "io.grpc:protoc-gen-grpc-java:1.22.3"
}
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
}
task.plugins {
lite { }
grpc { // Options added to --grpc_out
option 'lite' }
}
}
}
}