【问题标题】:Check always location services are enabled or not in React Native (iOS and Android both)检查始终在 React Native 中启用或未启用位置服务(iOS 和 Android 两者)
【发布时间】:2019-11-08 08:49:40
【问题描述】:

我正在开发 React Native 应用程序。如果用户从一个地方移动/导航到另一个地方,我必须在那里获取多个用户位置。这工作正常,但是,如果用户在一段时间后禁用位置权限,比如用户进入设置禁用权限,我必须显示一些按钮,如启用位置,然后再次显示一旦用户点击该按钮,它应该要求请求位置权限。

但是,如果用户第一次授予权限,并且稍后如果他禁用权限,则请求权限的弹出窗口不会在点击按钮时在 Android 中显示弹出窗口。

我正在使用以下库来获取用户位置详细信息。

import Geolocation from 'react-native-geolocation-service';

// button on click method following
  enableLocationHandler = () => {
    if (Platform.OS === 'android') {
      this.requestLocationPermissions();
    } else {
      Linking.openURL('app-settings:');
      this.getLatitudeLongitude();
    }
  }



requestLocationPermissions = async () => {
    if (Platform.OS === 'android') {
        this.getLatitudeLongitude();
    } else {
      Geolocation.requestAuthorization();
      this.getLatitudeLongitude();
    }
  }



 getLatitudeLongitude() {
    Geolocation.getCurrentPosition((position) => {
      const initialPosition = JSON.stringify(position);
    },
      (error) => {
        if (error.code === 1) {
          this.setState({ errorMessage: 'Location permission is denied', isLoading: false });
          Geolocation.clearWatch(this.watchID);
        }
      },
      { enableHighAccuracy: true, distanceFilter: 100, timeout: 20000, maximumAge: 1000 }
    );
    this.watchID = Geolocation.watchPosition((position) => {
      // this.showLoader();
      // console.log('position', position);
    });
  }

有什么建议吗?

【问题讨论】:

  • 如果Android和iOS一样,那么权限请求只显示一次。如果用户更改了设备设置中的权限,那么他们必须将它们更改回相同的位置。您所能做的就是显示一个警报,要求用户重新进入设置以启用位置权限

标签: javascript android ios react-native geolocation


【解决方案1】:

在这个插件 react-native-geolocation-service 中,android 中没有声明运行时权限。那是在 android 中,没有显示权限对话框。

要解决此问题,请在请求获取位置之前添加此权限

import {PermissionsAndroid} from 'react-native';

async function requestAccessLocationPermission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS. ACCESS_FINE_LOCATION,
      {
        title: 'Application wants location Permission',
        message:
          'Application wants location Permission',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
    } else {
    }
  } catch (err) {
    console.warn(err);
  }
}

这对你有帮助,对我也有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2021-12-28
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    相关资源
    最近更新 更多