Debug正常Release崩溃:谷歌地图Direction API混淆规则求助
谷歌地图Directions API Release版本崩溃的ProGuard解决方案
集成谷歌地图Directions API后,Debug构建运行正常,但Release构建出现NullPointerException,崩溃点在route.overviewPolyline处,原因是ProGuard混淆破坏了谷歌地图相关模型类的序列化/反序列化逻辑。
需要添加的ProGuard规则
# 保留谷歌地图Directions API相关类不被混淆 -keep class com.google.maps.model.** { *; } # 保留模型类的字段与构造方法,确保JSON解析正常 -keepclassmembers class com.google.maps.model.** { <fields>; <init>(...); }
规则说明
这些规则会保护com.google.maps.model包下的所有类(包括DirectionsResult、DirectionsRoute、EncodedPolyline等核心模型)不被混淆,确保API返回的JSON数据能正确映射到对应的对象实例,避免因字段丢失、构造方法被移除导致的对象为空问题。
相关代码
private void getDirections() { DirectionsResult result = getDirectionsDetails("place_id:" + pickupPlaceID, "place_id:" + dropPlaceID, TravelMode.DRIVING); if (result != null) { addPolyline(result); positionCamera(result.routes[0]); } } private DirectionsResult getDirectionsDetails(String origin, String destination, TravelMode mode) { return DirectionsApi.newRequest(geoApiContext).mode(mode).origin(origin).destination(destination).await(); } private void addPolyline(DirectionsResult results) { try { DirectionsRoute[] routes = results.routes; DirectionsRoute route = routes[0]; EncodedPolyline overviewPolyline = route.overviewPolyline; // 崩溃发生在此处 String encodedPath = overviewPolyline.getEncodedPath(); List<LatLng> decodedPath = PolyUtil.decode(encodedPath); nGoogleMap.addPolyline(new PolylineOptions().addAll(decodedPath)); } catch (Exception e) { e.printStackTrace(); } }
崩溃日志
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference System.err com.example.newapp at com.example.newapp.ui.home.HomeFragment.lambda$addPolyline$30(HomeFragment.java:1110)
内容的提问来源于stack exchange,提问作者Mohanasundar
相关产品推荐
相关产品推荐

