How do I request permission for Android Device Location in React Native at run-time?
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()
}
This did not work for me
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
}
I referred to https://facebook.github.io/react-native/docs/permissionsandroid.html#request and check() return a boolean
const granted = await PermissionsAndroid.check( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION );
if (granted) {
console.log( "You can use the ACCESS_FINE_LOCATION" )
}
else {
console.log( "ACCESS_FINE_LOCATION permission denied" )
}
You could use the react native PermissionsAndroid to request the permission: https://facebook.github.io/react-native/docs/permissionsandroid.html#request
Or, an easier option will be using a library that does it for you, such as https://github.com/yonahforst/react-native-permissions