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. In this tutorial we would going to Create Torch Flashlight Application for both Android & iOS react native applications and turn on off the flashlight on button click. We can also run the flashlight after minimizing the application as background.
Note: To access the android mobile phone camera we need to approve the camera run time permission in android.
Contents in this project Create Torch Flashlight Application in Android iOS React Native App Example.
1. Open your react native project folder in CMD or Terminal and execute the below command to install the React Native Torch library.
1
|
npm install —save react–native–torch
|
Screenshot of CMD:
Screenshot of CMD after successfully installed the library:
2. 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.
1
|
react–native link
|
Screenshot of CMD :
3. To access the Flashlight we need to first access the camera in our react native android app. So we need to authorize the CAMERA runtime permission.
Goto ReactNativeProject ->android ->app->src->main->AndroidManifest.xml file.
Put the below camera permission in it.
1
|
<uses–permission android:name=“android.permission.CAMERA”/>
|
Now define the USES-SDK versions and save the file.
1
2
3
|
<uses–sdk android:minSdkVersion=“16”
android:targetSdkVersion=“23”
/>
|
Source code of AndroidManifest.xml file after done above changes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<manifest xmlns:android=“http://schemas.android.com/apk/res/android”
package=“com.app”>
<uses–permission android:name=“android.permission.INTERNET” />
<uses–permission android:name=“android.permission.SYSTEM_ALERT_WINDOW”/>
<uses–permission android:name=“android.permission.CAMERA”/>
<uses–sdk android:minSdkVersion=“16”
android:targetSdkVersion=“23”
/>
<application
android:name=“.MainApplication”
android:label=“@string/app_name”
android:icon=“@mipmap/ic_launcher”
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>
|
4. Open ReactNativeProject ->android ->app->build.gradle file. Change the targetSdkVersion to 23 like i did in below example, This step is very important.
Source code of build.gradle file :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
apply plugin: “com.android.application”
import com.android.build.OutputFile
project.ext.react = [
entryFile: “index.js”
]
apply from: “../../node_modules/react-native/react.gradle”
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId “com.app”
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion 23
versionCode 1
versionName “1.0”
ndk {
abiFilters “armeabi-v7a”, “x86”
}
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include “armeabi-v7a”, “x86”
}
}
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile(“proguard-android.txt”), “proguard-rules.pro”
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
def versionCodes = [“armeabi-v7a”:1, “x86”:2]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
compile project(‘:react-native-torch’)
implementation fileTree(dir: “libs”, include: [“*.jar”])
implementation “com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}”
implementation “com.facebook.react:react-native:+” // From node_modules
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into ‘libs’
}
|
5. Import Platform, StyleSheet, View, PermissionsAndroid, Text, Alert and TouchableOpacity component in your react native project’s App.js file.
1
2
3
|
import React, { Component } from ‘react’;
import { Platform, StyleSheet, View, PermissionsAndroid, Text, Alert, TouchableOpacity } from ‘react-native’;
|
6. Import Torch component from react-native-torch library in your react native project.
1
|
import Torch from ‘react-native-torch’;
|
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. If you want to learn more about Requesting Runtime permission then you can read my this tutorial.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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)
}
}
|
8. Create the ASYNC componentDidMount() method in your main App’s export default class. We would call the request_camera_runtime_permission() method using await.
1
2
3
4
5
|
async componentDidMount() {
await request_camera_runtime_permission()
}
|
9. Create 2 function named as on_Torch() and off_Torch() to turn on and off the mobile phone flashlight.
1
2
3
4
5
6
7
8
9
10
11
|
on_Torch() {
Torch.switchState(true); // Turn ON the Torch.
}
off_Torch() {
Torch.switchState(false); // Turn OFF the Torch.
}
|
10. Creating 2 buttons in render’s return block using Touchable Opacity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
render() {
return (
<View style={styles.MainContainer}>
<TouchableOpacity onPress={this.on_Torch.bind(this)} activeOpacity={0.6} style={styles.button} >
<Text style={styles.TextStyle}> TURN ON TORCH </Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.off_Torch.bind(this)} activeOpacity={0.6} style={styles.button} >
<Text style={styles.TextStyle}> TURN OFF TORCH </Text>
</TouchableOpacity>
</View>
);
}
|
11. Creating Style.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
paddingTop: (Platform.OS) === ‘ios’ ? 20 : 0,
justifyContent: ‘center’,
margin: 20
},
button: {
width: ‘100%’,
paddingTop: 12,
paddingBottom: 12,
backgroundColor: ‘#FF6F00’,
borderRadius: 7,
marginTop: 10
},
TextStyle: {
color: ‘#fff’,
textAlign: ‘center’,
}
});
|
12. Complete source code for App.js File :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
import React, { Component } from ‘react’;
import { Platform, StyleSheet, View, PermissionsAndroid, Text, Alert, TouchableOpacity } 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()
}
on_Torch() {
Torch.switchState(true); // Turn ON the Torch.
}
off_Torch() {
Torch.switchState(false); // Turn OFF the Torch.
}
render() {
return (
<View style={styles.MainContainer}>
<TouchableOpacity onPress={this.on_Torch.bind(this)} activeOpacity={0.6} style={styles.button} >
<Text style={styles.TextStyle}> TURN ON TORCH </Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.off_Torch.bind(this)} activeOpacity={0.6} style={styles.button} >
<Text style={styles.TextStyle}> TURN OFF TORCH </Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
paddingTop: (Platform.OS) === ‘ios’ ? 20 : 0,
justifyContent: ‘center’,
margin: 20
},
button: {
width: ‘100%’,
paddingTop: 12,
paddingBottom: 12,
backgroundColor: ‘#FF6F00’,
borderRadius: 7,
marginTop: 10
},
TextStyle: {
color: ‘#fff’,
textAlign: ‘center’,
}
});
|
Screenshots: