How to check if user has granted camera permission in React Native Android?
Asked Answered
J

4

5

Right after the app launches, I am getting permission to use Camera from the user. But before opening camera if I check if the user has granted camera permission or not, I get the response as "false" even when it is allowed.

Here is my code:

PermissionsAndroid.check('camera').then(response => {
            if (response === true){
                //Open scanner
            }
            else if (response === false){
                Alert("Please enable camera permission in device settings.")
            }
        })
Judgment answered 7/6, 2018 at 6:44 Comment(0)
L
15

Please try as following:

PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.CAMERA).then(response => { ..

and not

PermissionsAndroid.check('camera').then(response => { ..
Louvre answered 7/6, 2018 at 6:53 Comment(0)
S
2

First import dependencies

import { PermissionsAndroid, Platform } from 'react-native';

Then use the following code on your event

if(Platform.OS=="android"){
      const permissionAndroid = await PermissionsAndroid.check('android.permission.CAMERA');
      if(permissionAndroid != PermissionsAndroid.RESULTS.granted){
        const reqPer = await PermissionsAndroid.request('android.permission.CAMERA');
        if(reqPer != 'granted'){
          return false;
        }
      }
    }
Secondhand answered 9/3, 2022 at 6:59 Comment(0)
T
1

Here I am using with async,await and promise, a little bit better to understand.

import {PermissionsAndroid} from 'react-native';

export const checkReadContactsPermission = async ()=>{    

  //result would be false if not granted and true if required permission is granted.
  const result =  await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.CAMERA);
  return result;
}
Taratarabar answered 23/8, 2020 at 19:18 Comment(0)
S
0

I tried above approaches but the return type of requesting permissions is changed to boolean value.

const permissionAndroid = await PermissionsAndroid.check('android.permission.CAMERA')
if (permissionAndroid != PermissionsAndroid.RESULTS.granted) {
  ...
} // this doesnt work

instead do this

const permissionAndroid = await PermissionsAndroid.check('android.permission.CAMERA')
if( permissionAndroid ){
...
}
Soto answered 7/4, 2023 at 7:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.