Reputation: 33
I'm trying to ask for runtime permission in ReactNative, but I'm always getting a "Permission is null" error in device screen.
here is the code:
import React, {Component} from 'react';
import {Text, View, StyleSheet, TextInput, Button} from 'react-native';
import {PermissionsAndroid} from 'react-native';
export default class HomeScreen extends React.Component {
componentDidMount()
{
PermissionsAndroid.request(PermissionsAndroid.READ_PHONE_STATE)
}
render () {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>Seja Bem vindo a BBTS!</Text>
<Text style={styles.paragraph}>
Matricula: {this.props.navigation.state.params.matricula}
</Text>
<Text style={styles.paragraph}>
Email: {this.props.navigation.state.params.email}
</Text>
<Text style={styles.paragraph}>
imei vem aqui
</Text>
</View>
);
}
}
I already put this on android manifest. My APi target is 26.
Any ideias?
Solution:
async requestPermission() {
try {
const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can read the phone state")
} else {
console.log("permission denied")
}
} catch (err) {
console.warn(err)
}
}
componentDidMount()
{
this.requestPermission();
}
Upvotes: 3
Views: 7012
Reputation: 47
I follow "PermissionsAndroid" bundle in "react-native" folder as
"./node_modules/react-native/Libraries/PermissionsAndroid"
Where you can see on all android permission for usage.
Upvotes: 0
Reputation: 7491
While you do need to handle the promise as @Daniel says the reason for the error is that your permissions request is incorrect, it should be:
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE)
Upvotes: 4
Reputation: 46
The request()
method returns a promise. You'll either need to async/await
or .then()/.catch()
and then check PermissionsAndroid.RESULTS.GRANTED
. That may either fix your problem or help you debug.
Upvotes: 3