How do I request permission for Android Device Location in React Native at run-time?

前端 未结 6 1888
后悔当初
后悔当初 2020-12-09 15:47

I have been trying to use React Native \'s GeoLocalisation for an Android App. The poorly documentated module is found here https://facebook.github.io/react-native/docs/geol

6条回答
  •  情歌与酒
    2020-12-09 16:36

    I solved it by changing the targetSdkVersion ( same to compileSdkVersion, in my case 23) in android/app/build.gradle.

    Edit AndroidManifest.xml located in android/src/main and add the

    
    
    

    next :

    import { PermissionsAndroid } from 'react-native';
    

    and then add this method:

    export async function requestLocationPermission() 
    {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            'title': 'Example App',
            'message': 'Example App access to your location '
          }
        )
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log("You can use the location")
          alert("You can use the location");
        } else {
          console.log("location permission denied")
          alert("Location permission denied");
        }
      } catch (err) {
        console.warn(err)
      }
    }
    

    and access the method when you request the location at run-time

    async componentWillMount() {
        await requestLocationPermission()
    }
    

提交回复
热议问题