我一直在尝试将React Native的GeoLocalisation用于Android应用程序。文档记录不佳的模块可在https://facebook.github.io/react-native/docs/geolocation.html找到。 根据文档,您使用AndroidManifest.xml文件中的以下代码处理Android上的位置权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
但是,我的在线研究表明上述代码行对于ANDROID&gt; = 6.0
的版本没用由于我的GeoLocation实现目前无效,我没有其他理由,只能相信未正确处理位置权限。
如何在运行时为React Native Android App成功请求位置权限? 提前谢谢!
答案 0 :(得分:15)
这对我不起作用
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
}
我提到https://facebook.github.io/react-native/docs/permissionsandroid.html#request 和check()返回一个布尔值
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" )
}
答案 1 :(得分:15)
我通过在android / app / build.gradle中更改了targetSdkVersion(与compileSdkVersion相同,在我的情况下为23)来解决了这个问题。
编辑位于android / src / main中的AndroidManifest.xml并添加
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
//下一个:
import { PermissionsAndroid } from 'react-native';
//,然后添加此方法:
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)
}
}
//,并在运行时请求位置时访问该方法
async componentWillMount() {
await requestLocationPermission()
}
答案 2 :(得分:3)
您可以使用react本机PermissionsAndroid来请求权限:https://facebook.github.io/react-native/docs/permissionsandroid.html#request
或者,更简单的选择是使用为您执行此操作的库,例如https://github.com/yonahforst/react-native-permissions
答案 3 :(得分:3)
这是我的代码,可同时获得Android和IOS中的当前位置
对于Android :
您需要在android AndroidManifest.xml文件中添加以下权限
对于IOS 您需要在Info.plist中包括NSLocationWhenInUseUsageDescription键,才能在使用应用程序时启用地理定位。当您创建带有react-native init的项目时,默认情况下会启用地理定位。
以下是查找当前位置(纬度和经度)的代码:
//This is an example code to get Geolocation//
import React from 'react';
//import react in our code.
import {View, Text, StyleSheet, Image ,PermissionsAndroid,Platform} from 'react-native';
//import all the components we are going to use.
export default class App extends React.Component {
state = {
currentLongitude: 'unknown',//Initial Longitude
currentLatitude: 'unknown',//Initial Latitude
}
componentDidMount = () => {
var that =this;
//Checking for the permission just after component loaded
if(Platform.OS === 'ios'){
this.callLocation(that);
}else{
async function requestCameraPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,{
'title': 'Location Access Required',
'message': 'This App needs to Access your location'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
//To Check, If Permission is granted
that.callLocation(that);
} else {
alert("Permission Denied");
}
} catch (err) {
alert("err",err);
console.warn(err)
}
}
requestCameraPermission();
}
}
callLocation(that){
//alert("callLocation Called");
navigator.geolocation.getCurrentPosition(
//Will give you the current location
(position) => {
const currentLongitude = JSON.stringify(position.coords.longitude);
//getting the Longitude from the location json
const currentLatitude = JSON.stringify(position.coords.latitude);
//getting the Latitude from the location json
that.setState({ currentLongitude:currentLongitude });
//Setting state Longitude to re re-render the Longitude Text
that.setState({ currentLatitude:currentLatitude });
//Setting state Latitude to re re-render the Longitude Text
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
that.watchID = navigator.geolocation.watchPosition((position) => {
//Will give you the location on location change
console.log(position);
const currentLongitude = JSON.stringify(position.coords.longitude);
//getting the Longitude from the location json
const currentLatitude = JSON.stringify(position.coords.latitude);
//getting the Latitude from the location json
that.setState({ currentLongitude:currentLongitude });
//Setting state Longitude to re re-render the Longitude Text
that.setState({ currentLatitude:currentLatitude });
//Setting state Latitude to re re-render the Longitude Text
});
}
componentWillUnmount = () => {
navigator.geolocation.clearWatch(this.watchID);
}
render() {
return (
<View style = {styles.container}>
<Image
source={{uri:'https://png.icons8.com/dusk/100/000000/compass.png'}}
style={{width: 100, height: 100}}
/>
<Text style = {styles.boldText}>
You are Here
</Text>
<Text style={{justifyContent:'center',alignItems: 'center',marginTop:16}}>
Longitude: {this.state.currentLongitude}
</Text>
<Text style={{justifyContent:'center',alignItems: 'center',marginTop:16}}>
Latitude: {this.state.currentLatitude}
</Text>
</View>
)
}
}
const styles = StyleSheet.create ({
container: {
flex: 1,
alignItems: 'center',
justifyContent:'center',
marginTop: 50,
padding:16,
backgroundColor:'white'
},
boldText: {
fontSize: 30,
color: 'red',
}
})
答案 4 :(得分:1)
您可以使用以下代码来请求位置许可
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
alert("You can use the location")
} else {
alert("Location permission denied")
}
} catch (err) {
console.warn(err)
}
alert('hi');
答案 5 :(得分:0)
我注意到两件事:
compileSdkVersion 23
档案中的build.gradle
示例代码:
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 (
<Text
onPress={() => this.requestLocationPermission()}>
Request Location Permission
</Text>
)
}
}
希望这会对你有所帮助。
答案 6 :(得分:0)
这对我有用
async requestCameraPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.props.navigation.navigate("MapScreen")
} else {
alert("Camera permission denied")
}
} catch (err) {
console.warn(err)
}
}
答案 7 :(得分:0)
在清单中
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.CAMERA"/>
import {PermissionsAndroid} from 'react-native';
async function requestCameraPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'Cool Photo App Camera Permission',
message:
'Cool Photo App needs access to your camera ' +
'so you can take awesome pictures.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('You can use the camera');
} else {
console.log('Camera permission denied');
}
} catch (err) {
console.warn(err);
}
}
export default class AlertDetails extends Component{
async componentDidMount() {
await request_storage_runtime_permission()
}
}