You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中通过gRPC调用Google Maps路线API报错求助

解决Android上gRPC调用谷歌Maps Routes的问题

1. 先确认依赖配置是否正确

  • 在build.gradle(Module)中添加必要的gRPC和Maps Routes依赖(版本可按需调整为最新稳定版):
    // gRPC核心依赖
    implementation 'io.grpc:grpc-android:1.59.0'
    implementation 'io.grpc:grpc-protobuf-lite:1.59.0'
    implementation 'io.grpc:grpc-stub:1.59.0'
    // Maps Routes gRPC客户端
    implementation 'com.google.maps.routing:routes-grpc-client:0.1.0'
    
  • 启用Java 8+支持,在build.gradle(Module)的android块中补充:
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    

2. 检查权限与网络配置

  • 在AndroidManifest.xml中添加网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • Android 9及以上需配置网络安全规则,允许访问谷歌服务:
    在res/xml/network_security_config.xml中写入:
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">googleapis.com</domain>
        </domain-config>
    </network-security-config>
    
    并在AndroidManifest.xml的application标签中引用:
    android:networkSecurityConfig="@xml/network_security_config"
    

3. 处理gRPC调用的线程限制

Android禁止主线程执行网络请求,必须将gRPC调用放在后台线程,示例用Coroutine实现:

lifecycleScope.launch(Dispatchers.IO) {
    try {
        val channel = ManagedChannelBuilder.forTarget("routes.googleapis.com:443")
            .useTransportSecurity()
            .build()
        val stub = RoutesGrpc.newBlockingStub(channel)
        
        val request = ComputeRouteDirectionsRequest.newBuilder()
            .setApiKey("你的谷歌云API密钥")
            // 填充起点、终点等请求参数
            .build()
            
        val response = stub.computeRouteDirections(request)
        
        // 切换回主线程处理结果
        withContext(Dispatchers.Main) {
            // 这里写UI更新逻辑
        }
        channel.shutdown()
    } catch (e: Exception) {
        e.printStackTrace()
        // 错误处理逻辑
    }
}

4. 排查google.maps.routing类相关错误

  • 若出现类找不到的错误,检查依赖是否同步成功,同时在proguard-rules.pro中添加混淆规则:
    -keep class com.google.maps.routing.** { *; }
    -keep class io.grpc.** { *; }
    -keep class com.google.protobuf.** { *; }
    
  • 确认你的谷歌云API密钥已启用Routes API权限,在谷歌云控制台的API密钥页面检查配置。

5. 关于Android兼容性说明

谷歌Maps Routes的gRPC客户端是支持Android平台的,只要配置正确即可正常运行,无需怀疑平台支持问题。

内容的提问来源于stack exchange,提问作者Hihellooo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 13:23:17