<?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 Naman Garg on Medium]]></title>
        <description><![CDATA[Stories by Naman Garg on Medium]]></description>
        <link>https://medium.com/@naman3garg?source=rss-eb542ba72f11------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m-xR0oScgTbi3D07MuD5tw.jpeg</url>
            <title>Stories by Naman Garg on Medium</title>
            <link>https://medium.com/@naman3garg?source=rss-eb542ba72f11------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:48:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naman3garg/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[How to Ensure a User’s Phone Number is Linked to an Active SIM on Their Device]]></title>
            <link>https://medium.com/@naman3garg/how-to-ensure-a-users-phone-number-is-linked-to-an-active-sim-on-their-device-51c958e40080?source=rss-eb542ba72f11------2</link>
            <guid isPermaLink="false">https://medium.com/p/51c958e40080</guid>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[phone-number-data]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[sim-card]]></category>
            <dc:creator><![CDATA[Naman Garg]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 13:20:47 GMT</pubDate>
            <atom:updated>2025-03-31T16:26:44.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xnuG1WoBLDZUm-Me" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will explore a step-by-step approach to verify if a user’s phone number is linked to an active SIM in their device or not in a React Native app using our custom React Native library supported on the React Native New Architecture.</p><h3>Step 1: Integrate the Required Dependencies</h3><pre>npm install react-native-simcard-info</pre><h3>Step 2: Add the required permissions</h3><p>Ensure that the necessary permissions are declared in the <strong>AndroidManifest.xml</strong> file inside android/app/src/main. These permissions are required to get the user phone number as mentioned <a href="https://developer.android.com/reference/android/telephony/SubscriptionManager#getPhoneNumber(int)">here</a> and <a href="https://developer.android.com/reference/android/telephony/SubscriptionInfo#getNumber()">here</a></p><pre>&lt;uses-permission android:name=&quot;android.permission.READ_PHONE_STATE&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.READ_PHONE_NUMBERS&quot; /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*4xPYYLOIYqD6Z_L8h6jXkw.png" /></figure><h3>Step 3: Retrieve the SIM Information</h3><p>In this step we will be retrieving the information of all the SIM cards currently present in the user’s device. Next we can display this list to the user to let them select a phone number of their choice which we can then start to track if they still have this number in their device or not.</p><pre>import { getActiveSIMInfoList } from &#39;react-native-simcard-info&#39;;<br><br>useEffect(()=&gt; {<br>  getActiveSIMInfoList();<br>}, []);<br><br>/* Begining of comment<br> Calling getActiveSIMInfoList() This will return an array of objects<br> where each object will have the following properties.<br>  {<br>    &quot;areUiccApplicationsEnabled&quot;: &quot;true&quot;,<br>    &quot;cardId&quot;: &quot;1&quot;,<br>    &quot;carrierConfigAccessRules&quot;: &quot;null&quot;,<br>    &quot;carrierId&quot;: &quot;2018&quot;,<br>    &quot;carrierName&quot;: &quot;Jio&quot;,<br>    &quot;countryIso&quot;: &quot;in&quot;,<br>    &quot;dataRoaming&quot;: &quot;0&quot;,<br>    &quot;displayName&quot;: &quot;SIM&quot;,<br>    &quot;displayNameSource&quot;: &quot;CARRIER_ID&quot;,<br>    &quot;ehplmns&quot;: &quot;[]&quot;,<br>    &quot;groupUuid&quot;: &quot;null&quot;,<br>    &quot;hplmns&quot;: &quot;[405872]&quot;,<br>    &quot;iconTint&quot;: &quot;#00796B&quot;,<br>    &quot;id&quot;: &quot;2&quot;,<br>    &quot;isEmbedded&quot;: &quot;false&quot;,<br>    &quot;isGroupDisabled&quot;: &quot;false&quot;,<br>    &quot;isOpportunistic&quot;: &quot;false&quot;,<br>    &quot;mType&quot;: &quot;LOCAL_SIM&quot;,<br>    &quot;mcc&quot;: &quot;405&quot;,<br>    &quot;mnc&quot;: &quot;872&quot;,<br>    &quot;nativeAccessRules&quot;: &quot;null&quot;,<br>    &quot;number&quot;: &quot;+911234567890&quot;,<br>    &quot;portIndex&quot;: &quot;-1&quot;,<br>    &quot;profileClass&quot;: &quot;-1&quot;,<br>    &quot;simSlotIndex&quot;: &quot;0&quot;,<br>    &quot;usageSetting&quot;: &quot;DEFAULT&quot;<br>  }<br>Out of the following, currently we are only interested in the `id` field <br>and the `number` field.<br>End of comment */ <br></pre><p>Once we call the following method, we can show the user a list of phone numbers to chose from. Next we will store the id of the selected option by user inside the async storage such that we can access it even after a user closes the application.</p><p><a href="https://developer.android.com/identity/user-data-ids#:~:text=The%20Subscription%20ID,on%20different%20devices.">NOTE </a>→ The subscriber ID is a unique positive number assigned by Android to a SIM card. While it uniquely identifies a SIM for a given phone number, it is not unique across different phone numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*le5gg3msjA3TVXmJQhemiQ.png" /></figure><h3>Step 4: Detecting change</h3><p>In this step, we will listen to the changes in user’s SIM activity to detect if the SIM associated with the given phone number is present in their device or not.</p><pre>const {simState} = useSIMStateChange();<br>/*<br>The value of the simState returns the same array of object which contain<br>information about each SIM Card present. You can use the above hook to listen<br>for any changes in the state of the SIM Card. <br>*/<br><br>function hasObjectWithId(array, id) {<br>  return array.some(obj =&gt; obj.id === id);<br>}<br><br>useEffect (() =&gt; {<br>  const storedId = 2; // get it from async storage<br>  const isSIMPresent = hasObjectWithId(simState, storedId);<br>}, [simState]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*TgMYaKU00kia0Y2SFMxj3g.png" /></figure><h3>Conclusion</h3><p>By following these steps, you can ensure that a user’s phone number is linked to an active SIM in their device. This improves security, enhances user experience, and prevents unauthorized access.</p><p>If you want to make some contributions to the library to make it better please feel free to make your contribution <a href="https://github.com/garg-lucifer/react-native-simcard-info">here</a>.</p><p>Suggestions and feedback are appreciated. I hope this blog was useful to you! See you later and thank you for taking the time to read this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51c958e40080" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Send Events from React Native to Android with the New Architecture]]></title>
            <link>https://medium.com/@naman3garg/how-to-send-events-from-react-native-to-android-with-the-new-architecture-b4c55eb81a31?source=rss-eb542ba72f11------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4c55eb81a31</guid>
            <category><![CDATA[new-architecture]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Naman Garg]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 19:36:54 GMT</pubDate>
            <atom:updated>2025-03-02T19:36:54.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J5vFiBUPrSTXdsdI" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we’ll explore how to emit events from React Native to Android, enabling seamless communication between JavaScript and native Android code. We’ll walk through setting up an event emitter, sending events from React Native, and handling them in Android. Whether you’re integrating native functionality or optimizing event-driven architecture, this guide will help you bridge the gap between React Native and Android efficiently.</p><h4>Step 1: Create a New React Native Architecture (Arch) Project</h4><p>To follow along, you need a React Native project with the new architecture enabled. You can create one using:</p><pre>npx @react-native-community/cli@latest init TurboModuleExample --version 0.76.0</pre><h4>Step 2: Create a Turbo Native Module</h4><p>With the <strong>New Architecture</strong>, we need to create a <strong>Turbo Native Module</strong> instead of the old-style native module. Inside your React Native project, create a TypeScript spec file: src/NativeSimcardInfo.ts</p><pre>import type { TurboModule } from &#39;react-native&#39;;<br>import { TurboModuleRegistry } from &#39;react-native&#39;;<br>import type { EventEmitter } from &#39;react-native/Libraries/Types/CodegenTypes&#39;;<br><br>export interface Spec extends TurboModule {<br>  readonly onAirplaneModeChange: EventEmitter&lt;boolean&gt;;<br>  readonly onSIMCardStateChange: EventEmitter&lt;Array&lt;Object&gt;&gt;;<br>}<br><br>export default TurboModuleRegistry.getEnforcing&lt;Spec&gt;(&#39;SimcardInfo&#39;);</pre><p>The above code defines a <strong>Turbo Native Module interface</strong> for React Native’s <strong>New Architecture</strong>. It declares two event emitters:</p><ul><li>onAirplaneModeChange: Emits a <strong>boolean</strong> value whenever airplane mode status changes.</li><li>onSIMCardStateChange: Emits an <strong>array of objects</strong> whenever there is a change in the SIM card state.</li></ul><p>This module is enforced using TurboModuleRegistry.getEnforcing&lt;Spec&gt;(&#39;SimcardInfo&#39;), ensuring that the native implementation is available.</p><h4>Important Note 🚨</h4><p>Make sure the file name starts with <strong>“Native”</strong>(NativeSimCardInfo.ts), as required by React Native’s <a href="https://reactnative.dev/docs/the-new-architecture/using-codegen#:~:text=Turbo%20Native%20Modules%20require%20that%20the%20spec%20files%20are%20prefixed%20with%20Native">Codegen</a>. I wasted hours debugging because I used a random name, and Codegen failed to generate the interface. Save yourself the trouble!</p><h4>Step 3: Configure Codegen to run</h4><p>To ensure that the <strong>Turbo Native Module</strong> works seamlessly, we need to configure <strong>Codegen</strong>. Codegen automatically generates the necessary native bindings for our module based on the TypeScript interface.</p><p>Enable Codegen in package.json by adding the following:</p><pre>  &quot;codegenConfig&quot;: {<br>    &quot;name&quot;: &quot;RNSimcardInfoSpec&quot;, // Any name works<br>    &quot;type&quot;: &quot;modules&quot;, // Depend if module or component or both<br>    &quot;jsSrcsDir&quot;: &quot;src&quot;,<br>    &quot;outputDir&quot;: {<br>      &quot;ios&quot;: &quot;ios/generated&quot;,<br>      &quot;android&quot;: &quot;android/generated&quot;<br>    },<br>    &quot;android&quot;: {<br>      &quot;javaPackageName&quot;: &quot;com.simcardinfo&quot;<br>    },<br>    &quot;includesGeneratedCode&quot;: true<br>  },</pre><p>After this run the following command. It will generate the necessary code for you in the background.</p><pre>cd android<br>./gradlew generateCodegenArtifactsFromSchema</pre><h4>Step 4: Write your Native Platform code</h4><p>Now that we’ve set up <strong>Codegen</strong>, it’s time to implement the <strong>native module</strong> in Android. This module will emit events from the Android side to React Native.</p><pre>package com.simcardinfo<br><br>class SimcardInfoModule(reactContext: ReactApplicationContext) :NativeSimcardInfoSpec(reactContext) {<br>  fun onAirplaneModeChanged(isAirplaneModeOn: Boolean) {<br>    emitOnAirplaneModeChange(isAirplaneModeOn)<br>  }<br>}</pre><p>This class SimcardInfoModule extends NativeSimcardInfoSpec, which is the <strong>auto-generated interface</strong> from Codegen. It ensures that our module correctly implements the TurboModule’s expected behavior.</p><p>For now, let’s assume that the onAirplaneModeChanged method is automatically called by Android whenever airplane mode changes. As soon as it&#39;s triggered, it invokes the event emitter <strong>emitOnAirplaneModeChange</strong>, which comes from the <strong>NativeSimcardInfoSpec</strong> interface. This sends the updated airplane mode status (true or false) to the JavaScript side, allowing React Native to react accordingly.</p><p>If you want to see how it is implemented under the hood please have a look below</p><pre><br>/**<br> * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).<br> *<br> * Do not edit this file as changes may cause incorrect behavior and will be lost<br> * once the code is regenerated.<br> *<br> * @generated by codegen project: GenerateModuleJavaSpec.js<br> *<br> * @nolint<br> */<br><br>package com.simcardinfo;<br><br>import com.facebook.proguard.annotations.DoNotStrip;<br>import com.facebook.react.bridge.ReactApplicationContext;<br>import com.facebook.react.bridge.ReactContextBaseJavaModule;<br>import com.facebook.react.bridge.ReactMethod;<br>import com.facebook.react.bridge.ReadableArray;<br>import com.facebook.react.bridge.WritableArray;<br>import com.facebook.react.bridge.WritableMap;<br>import com.facebook.react.turbomodule.core.interfaces.TurboModule;<br>import javax.annotation.Nonnull;<br><br>public abstract class NativeSimcardInfoSpec extends ReactContextBaseJavaModule implements TurboModule {<br>  public static final String NAME = &quot;SimcardInfo&quot;;<br><br>  public NativeSimcardInfoSpec(ReactApplicationContext reactContext) {<br>    super(reactContext);<br>  }<br><br>  @Override<br>  public @Nonnull String getName() {<br>    return NAME;<br>  }<br><br>  protected final void emitOnAirplaneModeChange(boolean value) {<br>    mEventEmitterCallback.invoke(&quot;onAirplaneModeChange&quot;, value);<br>  }<br><br>  protected final void emitOnSIMCardStateChange(ReadableArray value) {<br>    mEventEmitterCallback.invoke(&quot;onSIMCardStateChange&quot;, value);<br>  }</pre><p>As you can see this was the interface generated by the Codegen for us and it contains the method we used above to emit the events to the react native.</p><h4>Note 🚨</h4><p>If you are interested in knowing how exactly the Airplane mode listener works and how does the SIM card change listener works please have a look <a href="https://github.com/garg-lucifer/react-native-simcard-info/blob/main/android/src/main/java/com/simcardinfo/SimcardInfoModule.kt">here</a>.</p><h4>Step 5: Create and registering the package</h4><p>Once the native module has been implemented, the next step is to create and register the package so that React Native can recognize and use it in the JavaScript/TypeScript layer.</p><p>Inside your Android module, create a new Java/Kotlin class that will serve as the package for your native module.</p><pre>package com.simcardinfo<br><br>import com.facebook.react.BaseReactPackage<br>import com.facebook.react.bridge.NativeModule<br>import com.facebook.react.bridge.ReactApplicationContext<br>import com.facebook.react.module.model.ReactModuleInfo<br>import com.facebook.react.module.model.ReactModuleInfoProvider<br>import java.util.HashMap<br><br>class SimcardInfoPackage : BaseReactPackage() {<br>  override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? {<br>    return if (name == SimcardInfoModule.NAME) {<br>      SimcardInfoModule(reactContext)<br>    } else {<br>      null<br>    }<br>  }<br><br>  override fun getReactModuleInfoProvider(): ReactModuleInfoProvider {<br>    return ReactModuleInfoProvider {<br>      val moduleInfos: MutableMap&lt;String, ReactModuleInfo&gt; = HashMap()<br>      moduleInfos[SimcardInfoModule.NAME] = ReactModuleInfo(<br>        SimcardInfoModule.NAME,<br>        SimcardInfoModule.NAME,<br>        false,  // canOverrideExistingModule<br>        false,  // needsEagerInit<br>        true,  // hasConstants<br>        false,  // isCxxModule<br>        true // isTurboModule<br>      )<br>      moduleInfos<br>    }<br>  }<br>}</pre><p>Now, we need to add the package to <strong>MainApplication.java</strong> (for Java) or <strong>MainApplication.kt</strong> (for Kotlin).</p><p>In android/app/src/main/java/com/yourapp/MainApplication.kt, modify getPackages:</p><pre>override fun getPackages(): List&lt;ReactPackage&gt; = listOf(<br>    MainReactPackage(),<br>    YourModulePackage() // Register your package here<br>)</pre><h4>Step 6: Verifying and Testing the Integration</h4><p>Now that the package is registered, it’s time to test if it works properly.</p><pre>import NativeSimcardInfo from &#39;./NativeSimcardInfo&#39;;<br>import type { EventSubscription } from &#39;react-native&#39;;<br><br>type AirplaneModeCallback = (isAirplaneModeOn: boolean) =&gt; void;<br><br>const onAirplaneModeChange = (<br>  fn: AirplaneModeCallback<br>): EventSubscription =&gt; {<br>  return NativeSimcardInfo.onAirplaneModeChange(fn);<br>}; <br><br>useEffect(() =&gt; {<br>   onAirplaneModeChange((status) =&gt; {<br>     console.log(&#39;Custom Implementation Airplane Mode&#39;, status);<br>   });<br> }, []);</pre><p>Integrating native modules into a React Native project can greatly enhance functionality by leveraging platform-specific capabilities. In this article, we walked through the process of creating, registering, and testing a native module to handle SIM card information and airplane mode detection.</p><p>We typically start and stop the event listeners to start listening to the events and can then stop them when required. If you want to see how it’s done, please have a look <a href="https://github.com/garg-lucifer/react-native-simcard-info/blob/main/android/src/main/java/com/simcardinfo/SimcardInfoModule.kt">here</a>.</p><p>If you found this guide helpful, consider sharing it with fellow developers! 🚀 Feel free to drop any questions or thoughts in the comments. Happy coding! 🎯</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4c55eb81a31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything you need to know about adding Notifications with Alarm Manager in Android]]></title>
            <link>https://proandroiddev.com/everything-you-need-to-know-about-adding-notifications-with-alarm-manager-in-android-cb94a92b3235?source=rss-eb542ba72f11------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb94a92b3235</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[alarmmanager]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Naman Garg]]></dc:creator>
            <pubDate>Mon, 26 Sep 2022 07:10:08 GMT</pubDate>
            <atom:updated>2022-09-26T07:10:08.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKmuGMaMmyh2mZaQsxaI6Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@epicantus?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Daria Nepriakhina 🇺🇦</a> on <a href="https://unsplash.com/s/photos/notifications?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Android provides a feature that enables you to schedule notifications for later. This is useful if users/developers need to do something later in time. For example, if you need the user to remind some task they set in the future in a to-do list application. This blog uses AlarmManager and Broadcast Receivers to achieve the same in android API level 26 or later.</p><blockquote><a href="https://developer.android.com/guide/background#:~:text=Alarms%20are%20a%20special%20use%20case%20that%20are%20not%20a%20part%20of%20background%20work.%20You%20should%20execute%20background%20work%20through%20the%20two%20solutions%20outlined%20above%2C%20coroutines%20and%20WorkManager.">Note </a>→ We will not be using the WorkManager API to schedule alarms since alarms are a special use case and are not the part of background work. Also the recommended way to execute exact time jobs is the AlarmManager.</blockquote><p><strong>Step 1: Set up the data class:</strong></p><p>Since I have used this data class with RoomDatabase it is annotated with Entity but not necessary otherwise. The main thing however is the <em>id</em> field that is a <a href="https://en.wikipedia.org/wiki/Primary_key">primary key</a> and later will be used to set multiple notifications at a time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f86a42eac620832fc5b2b788a5bf38/href">https://medium.com/media/87f86a42eac620832fc5b2b788a5bf38/href</a></iframe><p><strong>Step 2. Set up the BroadcastReceiver class:</strong></p><p>This class will be called by our AlarmManager at some specific time in the future and this class will fire the notification at that instant. We need to add the notification inside this class. Some main things to consider while adding a notification are —</p><ol><li><em>setContentIntent()</em> = It takes a pending intent that will fire when a user taps the notification. PendingIntent here takes four parameters that are <em>context</em>, <em>requestCode</em>, <em>intent, </em>and a <em>flag</em>. Make sure to add one of the flags as <em>FLAG_IMMUTABLE </em>since it is necessary for the latest APIs.</li><li><em>setAutoCancel() = </em>It determines whether the notification will disappear or not when the user taps on it.</li><li><em>tapResultIntent.flags</em> = Make sure to add the intent flag ar your own convenience. I’m using <em>FLAG_ACTIVITY_SINGLE_TOP </em>because this app uses single activity multiple fragment model and at any instance, there exists only MainActivity at the top of the stack and when a user taps the notification when the app is in the foreground, it does not create any new instance of the activity.</li><li><em>NotificationCompat.Builder()</em> = It takes <em>context </em>and <em>channel_id </em>as parameters and we need to make sure the <em>channel_id </em>is the same as the <em>channel_id </em>we will use later to create the notification channel.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/745d3e0f623b3bcb2e04837139269d43/href">https://medium.com/media/745d3e0f623b3bcb2e04837139269d43/href</a></iframe><p>This class here receives the taskInfo object as intent in order to display the description of the notification as taskInfo.description and later to perform some tasks when we’ll add an action button to the notification. Also, don’t forget to add this class inside the manifest file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c75d5ec3a6e4bcbadba9851ad30bfcce/href">https://medium.com/media/c75d5ec3a6e4bcbadba9851ad30bfcce/href</a></iframe><p><strong>Step 3: Set the alarm</strong></p><p>We will be using the <a href="https://developer.android.com/reference/android/app/AlarmManager#setAlarmClock(android.app.AlarmManager.AlarmClockInfo,%20android.app.PendingIntent)"><em>setAlarmClock()</em></a><em> </em>method to set an alarm since I found it to be the most reliable when setting multiple alarms in the future. There are multiple methods to set an alarm as well such as —</p><ol><li><a href="https://developer.android.com/reference/android/app/AlarmManager#set(int,%20long,%20android.app.PendingIntent)">set()</a></li><li><a href="https://developer.android.com/reference/android/app/AlarmManager#setExact(int,%20long,%20android.app.PendingIntent)">setExact()</a></li><li><a href="https://developer.android.com/reference/android/app/AlarmManager#setInexactRepeating(int,%20long,%20long,%20android.app.PendingIntent)">setInExactRepeating()</a></li><li><a href="https://developer.android.com/reference/android/app/AlarmManager#setRepeating(int,%20long,%20long,%20android.app.PendingIntent)">setRepeating()</a></li><li><a href="https://developer.android.com/reference/android/app/AlarmManager#setTime(long)">setTime()</a></li><li><a href="https://developer.android.com/reference/android/app/AlarmManager#setTimeZone(java.lang.String)">setTimeZone()</a></li><li><a href="https://developer.android.com/reference/android/app/AlarmManager#setAndAllowWhileIdle(int,%20long,%20android.app.PendingIntent)">setAndAllowWhileIdle()</a></li><li><a href="https://developer.android.com/reference/android/app/AlarmManager#setExactAndAllowWhileIdle(int,%20long,%20android.app.PendingIntent)">setExactAndAllowWhileIdle()</a></li><li><a href="https://developer.android.com/reference/android/app/AlarmManager#setWindow(int,%20long,%20long,%20android.app.PendingIntent)">setWindow()</a></li></ol><p>In the <em>setAlarm(taskInfo: TaskInfo)</em> function we first create an instance of alarm manager and then set a pending intent to open the AlarmReciver class in the future which will then fire the notification. Notice that we have used <em>taskInfo.id </em>as the <em>requestCode </em>which will make sure that we have different <em>requestCode </em>for each alarm and thus can create multiple alarms with multiple notifications.</p><p><strong>Some things about the <em>setAlarmClock</em>() -</strong></p><p>Using this method the alarm clock icon will appear in the user’s status bar as if they had set an alarm with their device’s built-in alarm clock app and when the user fully slides open their notification, they will see the time of the alarm. Tapping on the alarm time in the notification will activate the PendingIntent we specified in the AlarmClockInfo object that is <em>basicPendingIntent </em>here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e78850d70d7968455eb03979a6f6f0c/href">https://medium.com/media/8e78850d70d7968455eb03979a6f6f0c/href</a></iframe><p>While setting any kind of exact alarm we need to add the <em>SCHEDULE_EXACT_ALARM </em>permission in the manifest file for the latest APIs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae42b871d869cec540e6bb6ebbd1ccc8/href">https://medium.com/media/ae42b871d869cec540e6bb6ebbd1ccc8/href</a></iframe><p><strong>Step 4: Create the notification channel</strong></p><p>Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel. For example, here we can create three channels for different task priorities set by users such as low, medium, and high each with a different visual and audio. NotificationChannel takes 3 parameters (<em>channel_id, channel_name, priority</em>). <em>channel_id </em>must be different for each channel and <em>channel_name </em>should describe basic info about the channel which can be viewed by the user inside the App Info. It only needs to be set up once and can be called inside the <em>onCreate() </em>method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b288ae87faab0a358a7c7dc561771a35/href">https://medium.com/media/b288ae87faab0a358a7c7dc561771a35/href</a></iframe><p><strong>Step 5: Cancelling the alarm(Optional)</strong></p><p>Let’s imagine we have a scheduled alarm for a task that the user wants to complete however it turned out the user has completed it way before that. In such a case we need to cancel the alarm. It is very easy to cancel the alarm, however, one must make sure that the <em>pendingIntent </em>used to cancel it<em> </em>must match the <em>pendingIntent </em>we used to set the alarm, or else it won’t cancel. It is not necessary to put the same content inside the <em>intent </em>we used previously because the contents inside the <em>intent </em>are not matched when comparing pending intents. (<em>such as intent.putExtra</em>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f332e757d50296386c8217e5431761c5/href">https://medium.com/media/f332e757d50296386c8217e5431761c5/href</a></iframe><p><strong>Step 6: Adding alarms when the device restarts</strong></p><p>When a device turns off, all alarms are canceled by default. To avoid this, we must design our application to automatically reset the alarm if the user reboots the device. This assures that the AlarmManager will continue to function without the user having to restart the alarm. We must add a broadcast receiver class that receives a broadcast whenever the device restarts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7f9063c2bd023b8e63944f430592a76/href">https://medium.com/media/c7f9063c2bd023b8e63944f430592a76/href</a></iframe><p>Here we are getting the list of all active alarms using our repository and setting the alarms back inside this class. Also, we need to add <em>RECEIVE_BOOT_COMPLETED </em>permission in the Android Manifest file along with the RebootBroadcastReceiver class and its intent filters. These intent filters enable it to receive the broadcast when either the device is restarted or switched on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae267d2d640035204acf36adef9b25be/href">https://medium.com/media/ae267d2d640035204acf36adef9b25be/href</a></iframe><blockquote>Note — In newer mobile phones you need to manually switch on the auto-launch feature inside App Info → Battery Management → AutoLaunch in order for it to receive the RECEIVE_BOOT_COMPLETED broadcast. It is turned off initially for battery management purposes. Basically it enables your application to auto launch whenever it receives the broadcast.</blockquote><p><strong>Step 7: Adding action button (Optional)</strong></p><p>Let’s say a user receives the notification for a task and has completed it, in that case, the user would like to press a finish/completed button so that it can be removed from the queue of uncompleted tasks. Now we’ll be adding an action button to complete a task. Here we will not be opening any activity when the user taps the button but performing some work in the background. For this, we need to add some code inside the AlarmReceiver class we created earlier and add another broadcast receiver class that will receive the broadcast to perform some action when a task is completed. Inside AlarmReceiver class we need to add one more pendingIntent that will be responsible to open OnCompletedBroadcastReceiver class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/774e0d83eaf327064d608de0d2d34e4e/href">https://medium.com/media/774e0d83eaf327064d608de0d2d34e4e/href</a></iframe><p>Also, add this class in the AndroidManifest.xml file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/096ba180b12838e1e1323a0a85ec0bcc/href">https://medium.com/media/096ba180b12838e1e1323a0a85ec0bcc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6cd4ca98209ac73bb3ac6351b09d77a/href">https://medium.com/media/a6cd4ca98209ac73bb3ac6351b09d77a/href</a></iframe><p>There are a few other things we can do with notifications, like adding a reply button and retrieving the notification’s user input text, but those are for another time.</p><p>Suggestions and feedback are appreciated. I hope this blog was useful to you! See you later and thank you for taking the time to read this.</p><p>You can find the link to the repository <a href="https://github.com/garg-lucifer/ToDoListApp"><strong>here</strong></a><strong> </strong>and you can connect with me on <a href="https://github.com/garg-lucifer"><strong>GitHub </strong></a>and <a href="https://www.linkedin.com/in/naman-garg-1b67371a1/"><strong>LinkedIn</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb94a92b3235" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/everything-you-need-to-know-about-adding-notifications-with-alarm-manager-in-android-cb94a92b3235">Everything you need to know about adding Notifications with Alarm Manager in Android</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>