Sunday, July 7, 2019

React Native Create Torch Flashlight Application

This tutorial explains how to create torch flashlight application in react native application. Flashlight is a important part of every mobile phone in current arena. It comes build in with each multimedia smartphone that comes with camera. Flashlight is basically used as camera flash in mobile phones but it can be also used as individual flashlight at night. In react naive there is no direct build in component available to control the flashlight manually but using the react-native-torch NPM library we can easily control both android and iOS mobile phones flashlight and make them turn on and off.

React Native Create Torch Flashlight Application


In this example, we will make a simple screen with a button to turn on/off the flashlight in react native application.

Turn On the Flashlight using :
Torch.switchState(true);

Turn Off the Flashlight using :
Torch.switchState(false);

Turn on/off Flashlight to Make a Torch App in React Native :

Lets see the complete source code App.js component that helps to create torch flashlight application in react native application.

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: Open your react native project folder in CMD or Terminal and execute the below command to install the React Native Torch library.
npm install --save react-native-torch

Step 3: After done installing the library we need to execute the link command in order to index the newly installed library in our current react native project.
react-native link react-native-torch

Step 4: To access the Flashlight we need to first access the camera and authorize the CAMERA runtime permission in react native android app. 

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

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

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"/>

    <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 5: Open App.js File in your favorite code editor and erase all code and follow this tutorial.

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

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

  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA,
      {
        'title': 'ReactNativeCode Camera Permission',
        'message': 'ReactNativeCode App needs access to your Camera.'
      }
    )

    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      Alert.alert("Camera Permission Granted.");
    }
    else {
      Alert.alert("Camera Permission Not Granted");
    }
  } catch (err) {
    console.warn(err)
  }
}

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

Step 9: Create turnONTorch and turnOFFTorch methods, which helps to provide flashlight turn on/off functionality.
  turnONTorch() {
    Torch.switchState(true); // Turn ON the Torch.
  }

  turnOFFTorch() {
    Torch.switchState(false); // Turn OFF the Torch.
  }

Step 10: Implement render method inside the App class and wrapped the below layout design inside the root View component.
 render() {
    return (
      <View style={styles.container} >
        <TouchableOpacity onPress={this.turnONTorch.bind(this)} activeOpacity={0.6} style={styles.button} >
          <Text style={styles.TextStyle}> TURN ON TORCH </Text>
        </TouchableOpacity>

        <TouchableOpacity onPress={this.turnOFFTorch.bind(this)} activeOpacity={0.6} style={styles.button} >
          <Text style={styles.TextStyle}> TURN OFF TORCH </Text>
        </TouchableOpacity>
      </View>
    );
  }

Step 11 : Apply the below style sheet design. 
const styles = StyleSheet.create(
  {
    container: {
      flex: 1,
      justifyContent: 'center',
      margin: 20
    },
    button: {
      width: '100%',
      paddingTop: 12,
      paddingBottom: 12,
      backgroundColor: '#2196f3',
      borderRadius: 7,
      marginTop: 10
    },
    TextStyle: {
      color: '#fff',
      textAlign: 'center',
    }
  });

Complete Source Code for App.js 

Lets see the complete source code that helps to create torch flashlight application in react native application.

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

export async function request_camera_runtime_permission() {

  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA,
      {
        'title': 'ReactNativeCode Camera Permission',
        'message': 'ReactNativeCode App needs access to your Camera.'
      }
    )

    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      Alert.alert("Camera Permission Granted.");
    }
    else {
      Alert.alert("Camera Permission Not Granted");
    }
  } catch (err) {
    console.warn(err)
  }
}


export default class App extends Component {

  async componentDidMount() {
    await request_camera_runtime_permission()
  }

  turnONTorch() {
    Torch.switchState(true); // Turn ON the Torch.
  }

  turnOFFTorch() {
    Torch.switchState(false); // Turn OFF the Torch.
  }

  render() {
    return (
      <View style={styles.container} >
        <TouchableOpacity onPress={this.turnONTorch.bind(this)} activeOpacity={0.6} style={styles.button} >
          <Text style={styles.TextStyle}> TURN ON TORCH </Text>
        </TouchableOpacity>

        <TouchableOpacity onPress={this.turnOFFTorch.bind(this)} activeOpacity={0.6} style={styles.button} >
          <Text style={styles.TextStyle}> TURN OFF TORCH </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create(
  {
    container: {
      flex: 1,
      justifyContent: 'center',
      margin: 20
    },
    button: {
      width: '100%',
      paddingTop: 12,
      paddingBottom: 12,
      backgroundColor: '#2196f3',
      borderRadius: 7,
      marginTop: 10
    },
    TextStyle: {
      color: '#fff',
      textAlign: 'center',
    }
  });

Screenshot : 

React Native Create Torch Flashlight Application

React Native Create Torch Flashlight Application

React Native Create Torch Flashlight Application


This is all about React Native Create Torch Flashlight ApplicationThank 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.


1 comment:

  1. thank you Mr. Sumit Kumar Pradhan this article is vary helpful of me

    ReplyDelete