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/geolocation.html. According to the documentation, you handle location permissions on Android using the following code in the AndroidManifest.xml
file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
However, my online research suggests that the above line of code is useless for versions of ANDROID >= 6.0
As my implementation of GeoLocation is not currently working, I have no other reason but to believe that location permissions are not correctly handled.
How do I successfully request location permission at run-time for React Native Android App ? Thanks in advance !
Geolocation is enabled by default when you create a project with react-native init . In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info. plist and add location as a background mode in the 'Capabilities' tab in Xcode.
So to ask permissions, React Native has a prebuilt feature in it which we can import and use it in our code. import { PermissionsAndroid } from 'react-native'; Before asking permissions to the user we have to declare that permissions in AndroidManifest.
checkSelfPermission(String perm); It returns an integer value of PERMISSION_GRANTED or PERMISSION_DENIED. Note: If a user declines a permission that is critical in the app, then shouldShowRequestPermissionRationale(String permission); is used to describe the user the need for the permission.
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
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With