使用本机反应检查是否启用了位置服务

Checking if location services are enabled using react native

我目前正在开发一款使用 React Native 的应用程序,该应用程序的某些功能需要启用定位服务。我一直在研究是否有一种简单的方法来测试用户是否打开了它们,这样我就可以在没有打开的情况下显示不同的视图。除了特定于 IOS 或 Android 的结果外,我没有找到任何结果。还有其他人找到解决方案吗?

我可以通过在无法检索位置时显示错误消息来解决此问题。

(error) => {
        this.setState({servicesOn: false}),
        console.log(error);
      },

将 "react native android location services dialog box" 模块用于 android

https://www.npmjs.com/package/react-native-android-location-services-dialog-box

安装

npm install react-native-android-location-services-dialog-box --save

js

import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";

LocationServicesDialogBox.checkLocationServicesIsEnabled({
  message: "Use Location ?",
  ok: "YES",
  cancel: "NO"
}).then(function(success) {
  console.log(success); // success => "enabled"
).catch((error) => {
  console.log(error.message); // error.message => "disabled"
});

执行 watchPosition 或 getCurrentPosition,您的第二个参数是失败时的回调,其参数是失败的原因。

所以,从那里你知道失败的时间和原因。例如,如果您只想对 'location disabled' 而不是 'request timed out' 采取行动,则需要一个 if 。

例如,您可以使用回调向您的状态添加标志。

您还可以试试这两个库:

https://github.com/c19354837/react-native-system-setting

https://github.com/efkan/react-native-system-settings

我有以下内容: 我收到此错误 代码 1 或错误消息:“没有可用的位置提供程序。”当我的 phone 定位服务关闭时。

其他时间,当它超时时,我收到此错误 代码 3 或错误消息:“位置请求超时。” .

因此,根据错误代码和消息,我显示不同的toasts来通知用户。

你可以参考MDN上的这个位置错误doc