如何使用 Flutter 跟踪后台位置?

k00*_*0ka 9 android location geolocation ios flutter

我一直在一个团队中工作,使用 Flutter 开发应用程序。我们需要使用 GPS 跟踪行驶的距离,但挑战在于Flutter 不再允许前景和后台位置跟踪(即使具有粗略的准确度)。

\n

根据对最新 Google 指南的审查,Google 似乎应该允许我们的应用程序在后台\xe2\x80\x99s 时跟踪设备,但事实并非如此。事实上,打开前台和后台定位服务似乎在一两个月前就起作用了。我们已经尝试过locationgeolocation软件包,但没有成功。当应用程序位于后台时,它们中的任何一个都会立即停止跟踪,并且当应用程序返回前台时,我们的位置会发生很大的跳跃。

\n

这里\xe2\x80\x99是我们\xe2\x80\x99尝试过的

\n
AndroidManifest.xml
\n
...\n<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>\n<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>\n...\n\n
Run Code Online (Sandbox Code Playgroud)\n
使用地理定位的应用程序代码
\n
...\nserviceEnabled = await Geolocator.isLocationServiceEnabled();\nif (!serviceEnabled) {\n return Future.error('Location services are disabled.');\n}\n\npermission = await Geolocator.checkPermission();\nif (permission == LocationPermission.denied) {\n permission = await Geolocator.requestPermission();\n if (permission == LocationPermission.denied) {\n   return Future.error('Location permissions are denied');\n }\n}\n\n//Permission returns denied Location \n//this is due to the background permission in the android manifest\n//turn off background permission and the permission is allowed\nif (permission == LocationPermission.deniedForever)\n return Future.error(\n     'Location permissions are permanently denied, we cannot request permissions.');\n}\n...\n
Run Code Online (Sandbox Code Playgroud)\n
使用位置的应用程序代码
\n
_serviceEnabled = await location.serviceEnabled();\nif (!_serviceEnabled) {\n _serviceEnabled = await location.requestService();\n if (!_serviceEnabled) {\n   print('Service could not be enabled');\n   return false;\n }\n\n// This code throws and exception even if I respond to the \n// Google prompts and I select allow location service and all the time access \ntry {\n await location.enableBackgroundMode(enable: true);\n} catch(error) {\n print("Can't set background mode");\n}\n
Run Code Online (Sandbox Code Playgroud)\n

任何有关如何实现这一目标的指导将不胜感激。

\n

小智 3

本质上,Flutter 仍然不支持后台本地化。

我见过一些android特定的形式,但没有任何效果。

但积极寻找,我发现了这个库:

https://pub.dev/packages/flutter_background_geolocation

它是一个付费库,可在生产中使用(适用于 Android 密钥。iOS 是免费的)。而且效果很好。

尽管有成本(这是独特的且终生的),但成本效益非常好。

强烈推荐。

注意:他们的文档和支持非常棒。