Sunday, July 7, 2019

React Native Runtime Permissions Request Android Example

This tutorial explains how to implement runtime permissions request in android device in react native application. The purpose of a permission is to protect the privacy of an Android user. Android apps must request permission to access sensitive user data (such as contacts and SMS), as well as certain system features (such as camera and internet). Depending on the feature, the system might grant the permission automatically or might prompt the user to approve the request. Android application has its own secure infrastructure to make application user feel that he is completely secure from any threat and also he can manage to give some of his own data as his own permissions. Application developer directly ask the application user for his permission before accessing his personal data like Device Location, Access Camera, Access device storage, Access device Contacts etc.

What is Android Permission?

According to Google’s privacy policy, a user should know which application is trying to access sensitive data such as contacts and SMS, as well as certain system features such as camera and internet. So in Android, they have introduced an Android permission modal in which applications have to ask for the permissions if they want to use user sensitive data or some certain features. The purpose of permission is to protect the privacy of an Android user.

Why We have to Ask for Permission?

Android applies the permission modal because some of the applications were tracking the user’s location in the background and accessing the private data like contacts, call history and messages without informing the App user which is the violation of googles privacy policy. So to solve this sensitive issue we have to ask for permission.



How to Ask for Permission in Android?

Now if you have an idea about the Android permission then have a look at how to ask for permission in Android.

To ask for permission in Android you have to follow two steps:

Step 1:  To ask for the permission you have to add those permissions requests in
 <Android project>/app/src/AndroidManifest.xml file.

For Example, if we want to ask for the Camera Permission we have to add the following permission request in AndroidManifest.xml

For example here is one line statement, that is require for camera permission.
<uses-permission android:name="android.permission.CAMERA">

React Native Runtime Permissions Request Android Example


After adding the permission in AndroidManifest file this permission will be automatically asked by the play store when they install the app and this permission will be granted to the applications.

NOTE: On devices before SDK version 23, the permissions are automatically granted if we add those permissions in our Androidmanifest.xml file but after SDK version 23 normal permissions are granted but for some permissions, you have to ask the user in runtime.

Step 2: After Google’s new permission modal they have introduced the run time permission mechanism. According to that, you have to include all the permissions in AndroidManiifest.xml but you have to ask for the dangerous permissions in run time.

NOTE : 
  • According to the official docs, dangerous permissions require a dialog prompt.
  • So whenever you are working with this dangerous permissions you need to check whether the permission is granted by the user or not and that can be done with the help of PermissionsAndroid in React Native.

For example, we have to ask for the INTERNET permission and CAMERA permission both but according to Android only CAMERA permission comes under the dangerous permission so we have to ask only for the CAMERA permission in run time. Hope you have understood the run time permission now.

How to Ask Run Time Android Permission using React Native PermissionsAndroid?

In React Native PermissionsAndroid component provides access to Android M (Over API level 23) new permissions model. You always need to check the permission before using native APIs which needs dangerous permissions.

You can check the permission granted or not using PermissionsAndroid.RESULTS.GRANTED

To ask for the permission you can use
PermissionsAndroid.request(permission name, {Permission dialog headng, body})

Run Time Permissions that Requires Confirmation from the User

Available as constants under PermissionsAndroid.PERMISSIONS

READ_CALENDARandroid.permission.READ_CALENDAR
WRITE_CALENDARandroid.permission.WRITE_CALENDAR
CAMERAandroid.permission.CAMERA
READ_CONTACTSandroid.permission.READ_CONTACTS
WRITE_CONTACTSandroid.permission.WRITE_CONTACTS
GET_ACCOUNTSandroid.permission.GET_ACCOUNTS
ACCESS_FINE_LOCATIONandroid.permission.ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATIONandroid.permission.ACCESS_COARSE_LOCATION
RECORD_AUDIOandroid.permission.RECORD_AUDIO
READ_PHONE_STATEandroid.permission.READ_PHONE_STATE
CALL_PHONEandroid.permission.CALL_PHONE
READ_CALL_LOGandroid.permission.READ_CALL_LOG
WRITE_CALL_LOGandroid.permission.WRITE_CALL_LOG
ADD_VOICEMAILcom.android.voicemail
USE_SIPandroid.permission.USE_SIP
PROCESS_OUTGOING_CALLSandroid.permission.PROCESS_OUTGOING_CALLS
BODY_SENSORSandroid.permission.BODY_SENSORS
SEND_SMSandroid.permission.SEND_SMS
RECEIVE_SMSandroid.permission.RECEIVE_SMS
READ_SMSandroid.permission.READ_SMS
RECEIVE_WAP_PUSHandroid.permission.RECEIVE_WAP_PUSH
RECEIVE_MMSandroid.permission.RECEIVE_MMS
READ_EXTERNAL_STORAGEandroid.permission.READ_EXTERNAL_STORAGE
WRITE_EXTERNAL_STORAGEandroid.permission.WRITE_EXTERNAL_STORAGE
Result Strings for Requesting Permissions

Available as constants under PermissionsAndroid.RESULTS:

ResponseResult
GRANTEDPermission granted successfully by the user
DENIEDPermission denied by the user
NEVER_ASK_AGAINPermission denied by the user with never ask again.
Note: These permissions would only work in device which has android operating system grater than Marshmallow or has Marshmallow 6.0 API Level 23. Below API Level 23 it will automatically grant all the permissions.

Lets see the below example to add runtime Permissions Request in react native example.

Step 1: Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step 2:  Add the permission in AndroidManifest.xml file. We are creating this example with device location permission so we are adding the device location permission known as ACCESS_FINE_LOCATION in AndroidManifest.xml file. You have to add your own permission here.

Goto ReactNativeProject ->android ->app->src->main->AndroidManifest.xml file.

Add the below location permission in it.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Once you add the permission in AndroidManifest.xml file, then file structure would look like this :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.rnv59">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

Step 3: Open App.js File in your favorite code editor and erase all code and follow this tutorial.

Step 4: Through react , react-native packages import all required components.
import React, { Component } from 'react';
import { PermissionsAndroid, Text, Alert, StyleSheet, View } from 'react-native';

Step 5: Create a ASYNC function named as request_location_runtime_permission(). This function is used to request the location runtime permission in android mobile phones.
export async function request_location_runtime_permission() {

  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        'title': 'ReactNativeCode Location Permission',
        'message': 'ReactNativeCode App needs access to your location '
      }
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      Alert.alert("Location Permission Granted.");
    }
    else {
      Alert.alert("Location Permission Not Granted");
    }
  } catch (err) {
    console.warn(err)
  }
}

Step 6: Create the ASYNC componentDidMount() method inside the App component. This method will call request_location_runtime_permission() method and helps to set the permission.
async componentDidMount() {
    await request_location_runtime_permission()
  }

Step 7: Implement render method inside the App class and wrapped the below layout design inside the root View component.
render() {
    return (
      <View style={styles.container} >
        <Text>React Native Runtime Permission Request</Text>
      </View>
    );
  }

Step 8 : Apply the below style sheet design. 
const styles = StyleSheet.create(
  {
    container: {
      flex: 1,
      justifyContent: 'center',
      margin: 20
    },
  });

Complete Source Code for App.js 

Lets see the complete source code that helps to add runtime permission request in react native application.

import React, { Component } from 'react';
import { PermissionsAndroid, Text, Alert, StyleSheet, View } from 'react-native';


export async function request_location_runtime_permission() {

  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        'title': 'ReactNativeCode Location Permission',
        'message': 'ReactNativeCode App needs access to your location '
      }
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      Alert.alert("Location Permission Granted.");
    }
    else {
      Alert.alert("Location Permission Not Granted");
    }
  } catch (err) {
    console.warn(err)
  }
}


export default class App extends Component {

  async componentDidMount() {
    await request_location_runtime_permission()
  }

  render() {
    return (
      <View style={styles.container} >
        <Text>React Native Runtime Permission Request</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create(
  {
    container: {
      flex: 1,
      justifyContent: 'center',
      margin: 20
    },
  });

Screenshot :

React Native Runtime Permissions Request Android Example

React Native Runtime Permissions Request Android Example

React Native Runtime Permissions Request Android Example

This is all about React Native Runtime Permissions Request Android Example. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment