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

前端 未结 6 1877
后悔当初
后悔当初 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:23

    I've noticed two things:

    1. You have to change compileSdkVersion 23 in build.gradle file
    2. You have to add your View's click listener to display to Permission dialog.

    Sample code:

    import React, { Component } from 'react';
    import { Text, PermissionsAndroid, Alert } from 'react-native';
    
    export default class RuntimePermissionSample extends React.Component {
    
        constructor(props) {
            super(props);
        }
    
        async requestLocationPermission() {
            const chckLocationPermission = PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
            if (chckLocationPermission === PermissionsAndroid.RESULTS.GRANTED) {
                alert("You've access for the location");
            } else {
                try {
                    const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                        {
                            'title': 'Cool Location App required Location permission',
                            'message': 'We required Location permission in order to get device location ' +
                                'Please grant us.'
                        }
                    )
                    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                        alert("You've access for the location");
                    } else {
                        alert("You don't have access for the location");
                    }
                } catch (err) {
                    alert(err)
                }
            }
        };
    
        render() {
            return (
                 this.requestLocationPermission()}>
                    Request Location Permission
                
            )
        }
    }
    

    Hope this would help you.

提交回复
热议问题