flutter geolocator Android国内定位失败问题解决

问题描述

在 Flutter 项目中使用 geolocator_android 插件时,默认会依赖 Google Play 服务进行 GPS 定位,国内无法使用。若需改用 Android 原生的 LocationManager,需保证 MethodCallHandlerImpl.java 文件中的 forceLocationManager 参数为true。

具体操作步骤

使用版本:geolocator: ^14.0.0

找到文件路径:
<flutter_project>/android/app/src/main/java/com/baseflow/geolocator/MethodCallHandlerImpl.java

修改代码逻辑:

onMethodCall 方法中,将 forceLocationManager 的默认值设为 true,强制使用原生定位:

java 复制代码
boolean forceLocationManager = true; // 默认改为 true

因为flutter中Geolocator.getCurrentPosition不支持同时设置locationSettingsforceAndroidLocationManager,所以直接修改安卓下forceLocationManager比较方便。也可以由flutter传递forceLocationManager的值,自行根据源码修改。

注意事项

  1. 文件路径可能因版本不同而变化
    geolocator_android 5.0.2 的文件路径为:
    <flutter_sdk>/.pub-cache/hosted/pub.flutter-io.cn/geolocator_android-5.0.2/android/src/main/java/com/baseflow/geolocator/MethodCallHandlerImpl.java

参考文献

https://blog.csdn.net/ZZB_Bin/article/details/121553574(要会员,不需要会员的转载:https://www.codeleading.com/article/91846452605/)
https://www.cnblogs.com/liumang/p/14675409.html