<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shayan Chatterjee on Medium]]></title>
        <description><![CDATA[Stories by Shayan Chatterjee on Medium]]></description>
        <link>https://medium.com/@shayanchatterjee7?source=rss-3d2b40a3b512------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kdrcIVV8j3KOq0fVTR37WA.jpeg</url>
            <title>Stories by Shayan Chatterjee on Medium</title>
            <link>https://medium.com/@shayanchatterjee7?source=rss-3d2b40a3b512------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:26:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shayanchatterjee7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Setting Up Multiple Environments in React Native (v0.74): Leveraging Android Product Flavors]]></title>
            <link>https://medium.com/@shayanchatterjee7/setting-up-multiple-environments-in-react-native-v0-74-d74574488e5d?source=rss-3d2b40a3b512------2</link>
            <guid isPermaLink="false">https://medium.com/p/d74574488e5d</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native-config]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[productflavor]]></category>
            <dc:creator><![CDATA[Shayan Chatterjee]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 20:15:40 GMT</pubDate>
            <atom:updated>2024-08-06T20:18:18.349Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Setting Up Multiple Environments in React Native (v0.74): Leveraging Android Product Flavors and Dimensions for Efficient Build Management — Part 1</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*785HuNtjnxsyxp6S4oP3aw.png" /></figure><p>In modern app development, managing multiple environments — such as development, staging, and production — is essential for ensuring smooth deployment and effective testing. Each environment often requires different configurations, API endpoints, and features, which can significantly impact the stability and functionality of your app.</p><p>Imagine your backend server is set up with separate environments for development, UAT (User Acceptance Testing), and production. As an app developer, you need to provide versions of your app that correspond to each of these environments. Each environment will likely have distinct API base endpoints, and you may also need to integrate different configurations for third-party SDKs, depending on the environment. Handling these variations efficiently is crucial for ensuring that your app functions correctly in each scenario without manual intervention or error-prone configuration changes.</p><p>So, how do you manage such scenarios effectively?</p><p>To address these challenges, Android’s Gradle build system offers powerful tools like buildTypes and productFlavors, which help manage different build configurations and environments effectively.</p><p>In this article in <strong>part 1</strong>, we will see how we can use these techniques for a React Native app for the Android side. In part 2 we will cover for <strong>iOS counterpart.</strong></p><p>We will assume we already have a React Native project setup done. In React native side, we will be using a package called react-native-config to help us setting up configurations based on different environement.</p><p>In this example, we will create 3 environments — dev (mostly used by developers), uat (mostly used by QA team for testing) and prod (app that is released on Play store or App store)</p><h3>Step 1</h3><p>At the root of the project, we will create 3 different env files simulating our 3 different environments and add the below two variables in each of our files —</p><p>.env.dev</p><pre>ENV=development<br>API_URL=https://myapidev.com</pre><p>.env.uat</p><pre>ENV=uat<br>API_URL=https://myapiuat.com</pre><p>.env.prod</p><pre>ENV=production<br>API_URL=https://myapiprod.com</pre><h3>Step 2</h3><p>Now, we will setup react-native-config in our react-native app. First do -</p><pre>yarn add react-native-config</pre><p>Open your android/app/build.gradle file and add the below line at the end of the file:</p><pre>apply from: project(&#39;:react-native-config&#39;).projectDir.getPath() + &quot;/dotenv.gradle&quot;</pre><p>In the same build.gradle file, add the below line inside the defaultConfig block -</p><pre>defaultConfig {<br>    ...<br>    resValue &quot;string&quot;, &quot;build_config_package&quot;, &quot;YOUR_PACKAGE_NAME_IN_ANDROIDMANIFEST_XML&quot;<br>}</pre><p>This is done to support different build variants we are going to create below.</p><blockquote>Pause!!</blockquote><p>In the same build.gradle file, you must have seen buildTypes block defined with debug and release inside them. What are these??</p><p>Before proceeding further, let’s first understand 3 terms — buildTypes, productFlavors and buildVariants</p><h3>Build Types</h3><p>buildTypes in Gradle define different versions of your app with distinct build settings, such as debug and release builds. The debug build type is typically used during development and testing, featuring additional logging and debugging capabilities. The release build type, on the other hand, is optimized for production and often includes minification and code obfuscation to enhance performance and security.</p><h3>Product Flavors</h3><p>productFlavors allow you to create multiple variants of your app, each tailored to different requirements or environments. For example, you might have flavors for development (dev), staging (uat), and production (prod). Each flavor can have its own configurations, resources, and dependencies.</p><h3><em>Build variants</em></h3><p>A build variant is a cross-product of build type and product flavor and is the configuration Gradle uses to build your app. Using build variants, you can build the debug version of your product flavors during development and signed release versions of your product flavors for distribution.</p><p>In short,</p><blockquote>buildVariant = productFlavors * buildTypes</blockquote><p>That is, for each productFlavor we are creating (like uat, dev, prod), it can have 2 different variant debug and release and together they form buildvariant.</p><blockquote>Let’s continue</blockquote><h3>Step 3</h3><p>We will add our 3 productFlavors defining our 3 environments below buildTypes block like this in android/app/build.gradle—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*hcOtAxevMOT5cXWaKBLvcQ.png" /></figure><p><strong>a.</strong> Here we are defining one of the dimensions to be <strong>environment </strong>in flavorDimensions. You can name it as you like.</p><p><strong>b.</strong> Then inside productFlavor, we create dev, uat, prod as 3 different flavors to be used. Each of them using the dimension <strong>environment</strong> which we have defined above. Each of them having its own minSdkVersion and targetSdkVersion.</p><p><strong>c.</strong>dev and uat flavors will have applicationIdSuffix as .dev and .uat respectively signifying whatever is the default applicationId defined in defaultConfig block above, for dev and uat flavours .dev and .uat will be appended to it. For prod, we will keep it same as applicationId defined in defaultConfig.</p><p>If you want to read, what this flavorDimension doing here, you can briefly read the below example, else can skip to step 4.</p><p><strong>flavourDimensions and </strong><strong>dimensions</strong></p><p>In Android’s Gradle build system, flavorDimensions and dimension are used to organize and manage multiple product flavors within different dimensions. Imagine you have another dimension, “featureSet,” with flavors free and paid. (free denoting free content for all users and paid denoting some paid content for exclusive users)</p><pre>flavorDimensions “environment”, “featureSet”<br><br>productFlavors {<br>    ...<br>    free {<br>        dimension &quot;featureSet&quot;<br>        applicationIdSuffix &quot;.free&quot;<br>    }<br>    paid {<br>        dimension &quot;featureSet&quot;<br>        applicationIdSuffix &quot;.paid&quot;<br>    }<br>}</pre><p>Here, combing with <strong>environment</strong> dimension, Gradle can create variants like devFree, devPaid, prodFree, prodPaid. This setup allows you to effectively manage and combine different configurations, environments, and feature sets in a scalable way.</p><h3>Step 4</h3><p>Next, we will create a map config, which will tell Gradle to load which env file for what buildVariant, like this —</p><pre>project.ext.envConfigFiles = [<br>    dev: “.env.dev”,<br>    uat: “.env.uat”,<br>    prod: “.env.prod”<br>]</pre><p>This map is used by the react-native-config to determine which .env file should be loaded based on the current build variant. All these .env files (like .env.dev have already been created in step 1).</p><p><strong>Note: </strong>All the key used above (like dev, uat and prod) should be in lowercase to correctly load the .env files.</p><h3>Step 5</h3><p>In the penultimate step, we will add some handy scripts in our package.json file to run the app in debug mode during development and also to create release APKs and production AABfor all these 3 environments —</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;android:dev-debug&quot;: &quot;react-native run-android --mode=devDebug&quot;,<br>    &quot;android:uat-debug&quot;: &quot;react-native run-android --mode=uatDebug&quot;,<br>    &quot;android:prod-debug&quot;: &quot;react-native run-android --mode=prodDebug&quot;,<br>    &quot;android:dev-release-apk&quot;: &quot;cd android &amp;&amp; ./gradlew clean &amp;&amp; ./gradlew assembleDevRelease &amp;&amp; cd .. &amp;&amp; echo &#39;find APK in android/app/build/outputs/apk/dev/release&#39;&quot;,<br>    &quot;android:uat-release-apk&quot;: &quot;cd android &amp;&amp; ./gradlew clean &amp;&amp; ./gradlew assembleUatRelease &amp;&amp; cd .. &amp;&amp; echo &#39;find APK in android/app/build/outputs/apk/uat/release&#39;&quot;,<br>    &quot;android:prod-release-apk&quot;: &quot;cd android &amp;&amp; ./gradlew clean &amp;&amp; ./gradlew assembleProdRelease &amp;&amp; cd .. &amp;&amp; echo &#39;find APK in android/app/build/outputs/apk/prod/release&#39;&quot;,<br>    &quot;android:prod-release-aab&quot;: &quot;cd android &amp;&amp; ./gradlew clean &amp;&amp; ./gradlew bundleProdRelease &amp;&amp; cd .. &amp;&amp; echo &#39;find AAB in android/app/build/outputs/apk/prod/release&#39;&quot;,<br>    &quot;start&quot;: &quot;react-native start&quot;<br>  }<br>}</pre><h4><strong>Understanding the scripts —</strong></h4><p>Here for android:dev-debug script, we run the run-android as it is like we do for running a normal react-native app with an additional flag of --mode here which is nothing but -</p><blockquote>buildVariant = productFlavors * buildTypes</blockquote><p>Remember the above analogy when we got to know what buildVariant is. Here productFlavor is dev and buildType is debug resulting in devDebug. Same is the case for uat-debug and prod-debug scripts as well.</p><p><strong>Note:</strong> Both devDebug and devdebug are valid here, as Gradle is case-insensitive when it comes matching build variants. Stick to one format (either camelCase or lowercase) across your scripts and configurations to avoid confusion and maintain readability.</p><p>For creating release APKs, we use</p><pre>./gradlew assembleDevRelease</pre><p>which tells Gradle to assemble the APK for devRelease build variant.</p><p>For creating AAB, we use</p><pre>./gradlew bundleProdRelease</pre><p>which tells Gradle to make an Android app bundle for prodRelease variant.</p><h3>Step 6</h3><p>We are done with all our settings and configurations. To verify the changes, we will load our ENV name and API_URL in React Native app using react-native-config package and can run different debug scripts defined above -</p><p>App.tsx</p><pre>import React from &#39;react&#39;;<br>import { SafeAreaView, StyleSheet, Text, useColorScheme } from &#39;react-native&#39;;<br>import { Colors } from &#39;react-native/Libraries/NewAppScreen&#39;;<br>import Config from &#39;react-native-config&#39;;<br><br>function App(): React.JSX.Element {<br>  const isDarkMode = useColorScheme() === &#39;dark&#39;;<br><br>  const backgroundStyle = {<br>    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,<br>  };<br><br>  return (<br>    &lt;SafeAreaView style={[backgroundStyle, styles.container]}&gt;<br>      &lt;Text&gt;ENV = {Config.ENV}&lt;/Text&gt;<br>      &lt;Text&gt;API = {Config.API_URL}&lt;/Text&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    justifyContent: &#39;center&#39;,<br>    alignItems: &#39;center&#39;,<br>  },<br>});<br>export default App;</pre><p>For example run,</p><pre>yarn android:uat-debug</pre><p>You should see the following screen in your android emulator/device —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqTmTRdXFKaR1IpuXRe5NA.png" /></figure><p>So that’s all. In Part 2, we will see how the same can be achieved for iOS as well.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d74574488e5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Determine installed UPI apps on a user device in React Native]]></title>
            <link>https://medium.com/@shayanchatterjee7/determine-installed-upi-apps-on-a-user-device-in-react-native-6ea290cbd52a?source=rss-3d2b40a3b512------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ea290cbd52a</guid>
            <category><![CDATA[upi-payment]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[upi]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native-modules]]></category>
            <dc:creator><![CDATA[Shayan Chatterjee]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 18:20:24 GMT</pubDate>
            <atom:updated>2023-06-19T18:20:24.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0MfypFqy14Gt9UkR2jD1w.jpeg" /></figure><p>We all must have all seen the case in the payment checkout screens of apps like Zomato or Swiggy, when we choose UPI as the payment mode, we are presented with a list of UPI apps installed on our device.</p><p>For example, if you have PhonePe and GPay installed, then only those UPI apps will be visible under the UPI payment mode. In this article, we will find how we can determine the installed UPI apps in a user’s device and can show those details in a React Native app.</p><p><strong>Note: This article for determining installed UPI apps is for Android devices only.</strong></p><p>We will take the following approach for doing this —</p><ol><li>Create a React Native project.</li><li>Creating a Native module for Android which will check for installed UPI apps.</li><li>Declaring the package name of the UPI apps we want to query in Manifest.</li><li>Invoking the Native Module in our React Native side and displaying those details in React Native app screen.</li></ol><p><strong>Step 1 —</strong></p><p>I will be skipping step 1 and will be assuming readers have the knowledge of setting up a basic React Native project (without expo since we are creating Native modules) and have a fair understanding of how React Native works with Native modules. Check out this docs if you are new to Native modules — <a href="https://reactnative.dev/docs/native-modules-android">https://reactnative.dev/docs/native-modules-android</a></p><p><strong>Step 2 —</strong></p><p>Next, we will be creating our Native Module for Android. We will be using Java here, but it can be easily be converted to Kotlin as well if we want.</p><p>Inside android/app/src/main/java/com/&lt;yourappname&gt;<em>, </em>create a file with the name UPIInstalledAppsModule.java<strong><em> (</em></strong>name it whatever you want!<strong><em>) </em></strong>and add the following piece of code —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cj0LU-DMW9Dnhm0LC_Sp9A.png" /></figure><p>Lets the see the above code in detail.</p><p>a. We have declared a class which extends ReactContextJavaModule. For Android, Java/Kotlin native modules are written as classes that extend ReactContextBaseJavaModule and implement the functionality required by JavaScript.</p><p>b. All Java/Kotlin native modules in Android need to implement the getName() method. This method returns a string, which represents the name of the native module. The native module can then be accessed in JavaScript using its name.</p><p>c. Next we will need to add a method to our native module that will create check for installed UPI apps and can be invoked in JavaScript. All native module methods meant to be invoked from JavaScript must be annotated with @ReactMethod. In our case below method written will be invoked for Javascript side —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IAvBsYWy_6XK-PFOPZEag.png" /></figure><p>Our method name is getInstalledUPIAppLists which either resolves or rejects a promise. All UPI apps must have the following URI scheme — upi://pay . So we are basically creating a URI in that format and setting that uri on an Intent object created using new Intent() . Then it obtains the PackageManager from the mReactContext using the getPackageManager() method. The PackageManager provides methods for querying and manipulating installed applications and their components.</p><p>It uses the PackageManager to query for activities that can handle the upiUriIntent by calling pm.queryIntentActivities(upiUriIntent, PackageManager.MATCH_DEFAULT_ONLY). This method returns a list of ResolveInfo objects, which contain information about activities that can handle the given intent. The MATCH_DEFAULT_ONLY flag restricts the search to only those activities marked as default handlers for the specified intent.</p><p>For the list obtained we are iterating over that list and obtaining three values and putting them inside a map —</p><ol><li>name — the actual name of the UPI app</li><li>code — the package name of the UPI app</li><li>icon — the Base64 string of the icon of the UPI app</li></ol><p>We are pushing each of this object inside an array and finally resolving our promise with the final array containg all the information of only the installed UPI apps. So each object inside the final array will have the following structure —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*glJknLhUNGp9IFipm77nBQ.png" /></figure><p><strong>Point to note:</strong></p><p>Notice that for icon key, we are using a custom utility class DrawableToBase64Util . So package manager gives us the icon of the UPI apps in Drawable format in Java. Since we need to show those images in our React Native side, we need a utility which can convert this Drawable to Base64 string so that we can display the icons using the Image component provided by React Native. Following is the code snippet of the utility class —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hyynsh90O5M8A7DONrpJhg.png" /></figure><p>Next, we have to create a package. Inside android/app/src/main/java/com/&lt;yourappname&gt;, create a file called UPIInstalledAppsPackage.java where we are creating our NativeModules and declaring which module we need to add (in our case UPIInstalledAppsModule which we just created above)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgUbv32EBk3dWluHq3qGaw.png" /></figure><p>For the last process in this step, to register the UPIInstalledAppsModule package, you must add UPIInstalledAppsPackage to the list of packages returned in ReactNativeHost’s getPackages() method. Open up your MainApplication.java or MainApplication.kt file, which can be found in the following path: android/app/src/main/java/com/&lt;yourappname&gt;</p><p><a href="http://twitter.com/Override">@Override</a><br>protected List&lt;ReactPackage&gt; getPackages() {<br> <a href="http://twitter.com/SuppressWarnings">@SuppressWarnings</a>(“UnnecessaryLocalVariable”)<br> List&lt;ReactPackage&gt; packages = new PackageList(this).getPackages();<br> <strong>packages.add(new UPIInstalledAppsPackage());</strong><br> return packages;<br>}</p><p>End of step 2!! Quite a long step!</p><p><strong>Step — 3-&gt; Package visibility</strong></p><p>On Android 10 and earlier, apps could query the full list of installed apps on the system using methods like queryIntentActivities(). But from Android 11 and later with ongoing focus on privacy, we need to specify which apps we actually want to query. This can be done by adding a &lt;queries&gt; element in the Android manifest. Open our AndroidManifest.xml file and add the following package name of the UPI apps inside the manifest tag —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiL5ymUknyBwbuN2qDGACg.png" /></figure><p>We can specify package name of more UPI apps if we want. But for now these are sufficient.</p><p><strong>Step — 4</strong></p><p>Next we need to invoke our native method we have just written in our JavaScript side. And this is fairly simple enough and can be done in the following way —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umaSLwvCgg1o2YFemLZUgg.png" /></figure><p>Here is the brief of what’s happening —</p><p>We have imported NativeModules from react-native and from that we have destructured our own native module with the name UPIInstalledAppsModule (remember the name we have given to our module in Java code!). Then inside the useEffect we are invoking our native method getInstalledUPIAppLists which return us the list of installed UPI apps and we are storing them inside our local state. Finally we are mapping over that state in our JSX and displaying those apps in our screen.</p><p>And here is the result —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*9RVuqpSqbHqbKGQjTDVt1g.jpeg" /></figure><p>On my device, I have GPay and Paytm installed and those are visible in my react native app. Great!!</p><p>That’s it for the article. Hope you have learnt something new from this.</p><p>I have also published an npm package for the same called <a href="https://www.npmjs.com/package/react-native-upi-apps"><strong><em>react-native-upi-apps</em></strong></a>. Check this out and use it if you want in your application!</p><p>Also you can checkout the complete GitHub repo link for the package <a href="https://github.com/Cshayan/react-native-upi-apps"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><p>Hope you have enjoyed reading this :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ea290cbd52a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a surrounding light sensor module (using Native Module) for Android device in React Native]]></title>
            <link>https://medium.com/engineering-at-bajaj-health/creating-a-surrounding-light-sensor-module-for-android-device-in-react-native-6a0f9fa7d13e?source=rss-3d2b40a3b512------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a0f9fa7d13e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[native-modules]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[light-sensor]]></category>
            <dc:creator><![CDATA[Shayan Chatterjee]]></dc:creator>
            <pubDate>Sun, 24 Jul 2022 18:39:14 GMT</pubDate>
            <atom:updated>2024-04-10T07:44:08.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*zd0lpRdRxa0UMSwDHnZGRw.jpeg" /></figure><p>A couple of days ago, I was working on a task in a React Native app where I need to automatically turn on the torch/flash light of the device when the user turns on the camera within the app and the surrounding environment has dim/dark light. The flash/torch light should be auto turned off again if the surrounding light becomes significantly brighter.</p><p>Naturally, I looked for some package in react native which can provide me some data about my surrounding’s light condition. Unfortunately, I did not get any such package/library which provides such functionality. So I did some research about this topic and came across SensorManager API for android. Basically SensorManager lets you access the device’s <a href="https://developer.android.com/reference/android/hardware/Sensor">sensors</a>.</p><p>Checkout the SensorManager API docs — <a href="https://developer.android.com/reference/android/hardware/SensorManager"><em>Docs Link</em></a></p><p>The hurdle here is that I can get the surrounding light data from the SensorManager but I need this value in my React Native JavaScript end so that I can turn on/off the flash light off the device based on the value.</p><p>Naturally, I had to write my own Native Module for android to perform this job. If you are new to Native Modules in React Native, check out their docs — <a href="https://reactnative.dev/docs/native-modules-intro">Native Modules Intro</a> . In short, sometimes as a developer we want to access some Native APIs of the device which are not available in Javascript. From their docs —</p><blockquote>The NativeModule system exposes instances of Java/Objective-C/C++ (native) classes to JavaScript (JS) as JS objects, thereby allowing you to execute arbitrary native code from within JS.</blockquote><p>I will list down the approach I have used —</p><ol><li>Create a Native Module which will implement the SensorEventListener interface. This interface provides two methods onSensoryChanged(SensorEvent event)and onAccuracyChanged(Sensor sensor, int accuracy)<em>, </em>which we need to override in our module.</li><li>Create a method which will send some kind of event with the current surroundings light value to the Javascript end.</li><li>Register a listener at Javascript side which will listen to the value changes to the device’s surrounding environment.</li><li>Lastly, turn on/off the device’s torch light based on the light value we receive from the listener.</li></ol><p><strong>Step 1 and Step 2 —</strong></p><p>First, create the LightSensorModule. Inside android/app/src/main/java/com/&lt;yourappname&gt;, create a file called LightSensorModule.java<em> </em>(you can name it whatever you want).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f8b4669c978daa22d22cd1770ce5c68/href">https://medium.com/media/1f8b4669c978daa22d22cd1770ce5c68/href</a></iframe><p>What it does —</p><p>a. It implements SensorEventListener<em> </em>interface and overrides its two methods onSensorChanged and onAccuracyChanged. We are interested in the method onSensorChanged which will give us the value whenever the sensor value changes.</p><p>b. In the constructor of our module, we are initializing our SensorManager API of TYPE_LIGHT for our case. Check out all the type of sensors present <a href="https://developer.android.com/reference/android/hardware/Sensor">here</a>.</p><p>c. We are creating two methods called startLightSensor and stopLightSensorwhich we will be invoking from our JavaScript side. startLightSensor<em> </em>registers a listener for the sensor manager of the device. stopLightSensor<em> </em>unregisters/destroys the invoked listener.</p><p>d. onSensorChanged<em> </em>overridden method receives the sensor event value in its param, inside it we are creating a map with key lightValue<strong><em> </em></strong>and storing the corresponding sensor event value with it.</p><p>e. In our last process, we are passing the map to a method called sendEvent<em> </em>which uses the DeviceEventManagerModule to send events with some event properties. This is the event for which we will listen to at our Javascript end and ultimately fetch the lightValue from it.</p><p>Next, we have to create a package. Inside android/app/src/main/java/com/&lt;yourappname&gt;, create a file called LightSensorPackage.java where we are creating our NativeModules and declaring which module we need to add (in our case LightSensorModule which we just created above)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83f71fb176f7f30bd56d5926132bdd3c/href">https://medium.com/media/83f71fb176f7f30bd56d5926132bdd3c/href</a></iframe><p>For the last process in this step, to register the LightSensorModulepackage, you must add LightSensorPackage to the list of packages returned in ReactNativeHost&#39;s getPackages() method. Open up your MainApplication.java or MainApplication.kt file, which can be found in the following path: android/app/src/main/java/com/your-app-name/</p><pre> @Override<br> protected List&lt;ReactPackage&gt; getPackages() {<br> @SuppressWarnings(“UnnecessaryLocalVariable”)<br> List&lt;ReactPackage&gt; packages = new PackageList(this).getPackages();<br> packages.<strong><em>add</em></strong>(<strong><em>new</em></strong> <strong><em>LightSensorPackage</em></strong>());<br> return packages;<br>}</pre><p>This ends our codes for native side. We now need to invoke these created methods in our JavaScript end.</p><p><strong>Step 3 and 4-</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f1ffb1b6530ede760d57a0429d8fe19/href">https://medium.com/media/3f1ffb1b6530ede760d57a0429d8fe19/href</a></iframe><p>Here, we are first starting our light sensor on the mount of the component inside the useEffect hook and also listening to the event with the name LightSensor<em> </em>which we are emitting from our native side code. The event value will be an object with a key lightValue<strong><em> </em></strong>that has the actual value of light (in unit called lux). Refer the below table to get an overall idea of the type of light values we can expect based on the surrounding environment.</p><p>Source — <a href="https://docs.microsoft.com/en-us/windows/win32/sensorsapi/understanding-and-interpreting-lux-values">Interpreting lux values</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*goGmjP61asNnIhfHcdMYqg.png" /></figure><p>Now, based upon the light value I can turn on/off the device’s torch light or you can do any logic as per your requirement. Lastly, we should stop the sensor from running in the background when not in use, hence invoking our second method <em>stopLightSensor </em>when the component unmounts.</p><p>So, that’s about it! We have created our Native Modules in android which uses our device’s light sensor to interpret the light value and we also checked how we can receive that value in our JavaScript end and perform any logic.</p><p>I have also published an npm package for the same called <a href="https://www.npmjs.com/package/react-native-ambient-light-sensor"><strong><em>react-native-ambient-light-sensor</em></strong></a><strong><em>. </em></strong>Check this out and use it if you want in your application!</p><p>Also you can checkout the complete GitHub repo link for the package <a href="https://github.com/Cshayan/react-native-ambient-light-sensor"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><p>Hope you have enjoyed reading this :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a0f9fa7d13e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-at-bajaj-health/creating-a-surrounding-light-sensor-module-for-android-device-in-react-native-6a0f9fa7d13e">Creating a surrounding light sensor module (using Native Module) for Android device in React Native</a> was originally published in <a href="https://medium.com/engineering-at-bajaj-health">Engineering at Bajaj Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>