构建GeoApiContext时触发IllegalStateException导致安卓应用崩溃
看起来你遇到的问题根源非常明确——从异常栈的核心错误就能定位:
java.lang.IllegalStateException: Expected Android API level 21+ but was 31
这是因为你使用的Google Maps Java客户端依赖的OkHttp版本过于老旧,旧版OkHttp在判断Android API等级时,没有适配API 30以上的系统(你的设备是API 31,对应Android 12),错误地把31识别成低于21的版本,直接触发了这个异常。
我给你整理了几个分步解决的方案:
1. 升级Google Maps服务客户端依赖
首先检查你Module级build.gradle里的Google Maps Java客户端依赖,换成最新的兼容版本,同时确保OkHttp版本匹配:
dependencies { // 替换为最新版的Google Maps服务客户端,比如当前最新稳定版是2.2.0 implementation 'com.google.maps:google-maps-services:2.2.0' // 引入兼容高API等级的OkHttp版本,避免依赖冲突 implementation 'com.squareup.okhttp3:okhttp:4.11.0' }
如果担心依赖冲突,可以主动排除Google Maps客户端自带的旧OkHttp:
implementation ('com.google.maps:google-maps-services:2.2.0') { exclude group: 'com.squareup.okhttp3', module: 'okhttp' } implementation 'com.squareup.okhttp3:okhttp:4.11.0'
2. 修正LatLng类型转换的潜在问题
另外看你的代码里,调用origin(currentLocation.toString())和destination(destinationLocation.toString())存在逻辑问题:Google Maps Java客户端的DirectionsApiRequest需要的是com.google.maps.model.LatLng类型,而非安卓SDK自带的com.google.android.gms.maps.model.LatLng的字符串。你需要做类型转换:
// 在onMapReady方法里替换这部分代码 com.google.maps.model.LatLng apiOrigin = new com.google.maps.model.LatLng(currentLocation.latitude, currentLocation.longitude); com.google.maps.model.LatLng apiDest = new com.google.maps.model.LatLng(destinationLocation.latitude, destinationLocation.longitude); DirectionsApiRequest directionsApiRequest = DirectionsApi.newRequest(context) .origin(apiOrigin) .destination(apiDest) .mode(TravelMode.WALKING);
这部分不是当前崩溃的原因,但提前修复能避免后续Directions API请求失败。
3. 额外验证点
- 再次核对
build.gradle里的编译和目标SDK版本,确保都设置为31或更高:
android { compileSdkVersion 34 defaultConfig { targetSdkVersion 34 // ...其他配置项 } }
- 升级依赖后,记得清理项目、重启Android Studio并重新构建,确保依赖更新生效。
按这个步骤操作,应该能解决构建GeoApiContext时的崩溃问题,同时也能规避后续API请求的潜在错误。
备注:内容来源于stack exchange,提问作者kinghabz 14

