آموزش React Native – ساخت اپلیکیشن flashlight


Flashlight یک بخش مهم از هر گوشی موبایل در حال حاظر است.فلش به همراه گوشی هایی با قابلیت فیلم برداری به همراه دوربین ساخته شد.Flashlight در اصل به عنوان فلش دوربین در گوشی های همراه استفاده می شود اما گاهی اوقات به عنوان چراغ قوه نیز استفاده می شود.در هسته React Native کامپوننتی برای کنترل flashlight وجود ندارد اما میتوان با استفاده از کتابخانه react-native-torch میتوان flashlight را در هر دو نسخه Android و Ios به راحتی کنترل و خاموش/روشن کرد.در این آموزش متنی قصد داریم یک اپلیکیشن Torch Flashlight با استفاده از React Native ایجاد کنیم.
1.باز کردن دایرکتوری پروژه در CMD یا Terminal و اجرای دستور زیر برای نصب کتابخانه React Native Torch
1 |
npm install --save react-native-torch |
2.بعد از نصب موفقیت آمیز کتابخانه باید دستور link کتابخانه رو اجرا کنیم
1 |
react-native link |
3.برای دسترسی به Flashlight ابتدا ما باید به Camera دسترسی پیدا کنیم.پس نیاز به دسترسی CAMERA runtime permission داریم.
به مسیر ReactNativeProject ->android ->app->src->main برید.و permission زیر را در فایل AndroidManifest.xml اضافه کنید.
1 |
<uses-permission android:name="android.permission.CAMERA"/> |
حالا USES-SDK را تعریف و فایل را ذخیره کنید
1 2 3 |
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="23" /> |
سورس کد فایل AndroidManifest.xml باید بعد از تغییرات به شکل زیر باشد.
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.فایل ReactNativeProject ->android ->app->build.gradle را بازکنید و targetSdkVersion را به 23 تغییر دهید.این مرحله بسیار مهم است.
سورس کد فایل build.gradle
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.کامپوننت های Platform, StyleSheet, View, PermissionsAndroid, Text, Alert و TouchableOpacity رو در فایل App.js ایمپورت کنید.
1 2 3 |
import React, { Component } from 'react'; import { Platform, StyleSheet, View, PermissionsAndroid, Text, Alert, TouchableOpacity } from 'react-native'; |
6.کامپوننت Torch را از کتابخانه react-native-torch ایمپورت کنید
1 |
import Torch from 'react-native-torch'; |
7.یک تابع ASYNC به نام ()request_camera_runtime_permission ایجاد کنید.این تابع برای درخواست دسترسی به camera به صورت runtime مورد استفاده قرار میگیرد.قبلا در آموزش متنی درخواست permission به صورت runtime در React Native این مورد رو کامل توضیح دادیم.
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.تعریف() componentDidMount به صورت ASYNC در فایل App.js.در این lifeCycle ما تابع () request_camera_runtime_permissionرا فراخوانی میکنیم.
1 2 3 4 5 |
async componentDidMount() { await request_camera_runtime_permission() } |
9.ایجاد دو تابع با نام های() on_Torch و() off_Torch برای خاموش و روشن کردن فلش.
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.ایجاد دو button و فراخوانی توابع بالا در رویداد onPress این دکمه ها
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.ایجاد استایل
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 : , justifyContent: 'center', margin: 20 }, button: { width: '100%', paddingTop: 12, paddingBottom: 12, backgroundColor: '#FF6F00', borderRadius: 7, marginTop: 10 }, TextStyle: { color: '#fff', textAlign: 'center', } }); |
12.کد کامل برنامه در فایل App.js
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 : , justifyContent: 'center', margin: 20 }, button: { width: '100%', paddingTop: 12, paddingBottom: 12, backgroundColor: '#FF6F00', borderRadius: 7, marginTop: 10 }, TextStyle: { color: '#fff', textAlign: 'center', } }); |
دیدگاهتان را بنویسید