<?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 Arjun Singh on Medium]]></title>
        <description><![CDATA[Stories by Arjun Singh on Medium]]></description>
        <link>https://medium.com/@arjun30?source=rss-dfeb2694285f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yEB9ReeMxzevBPoL.</url>
            <title>Stories by Arjun Singh on Medium</title>
            <link>https://medium.com/@arjun30?source=rss-dfeb2694285f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 14:14:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arjun30/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 start with Coroutine in Android]]></title>
            <link>https://arjun30.medium.com/how-to-start-with-coroutine-in-android-7c54009f0037?source=rss-dfeb2694285f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c54009f0037</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 08:00:24 GMT</pubDate>
            <atom:updated>2023-07-25T08:00:24.600Z</atom:updated>
            <content:encoded><![CDATA[<p>Asynchronous programming is a crucial aspect of Android development, enabling us to perform time-consuming tasks without blocking the main thread. Traditionally, callbacks and threads were used to handle asynchronous operations, but they could lead to complex, error-prone code. With the introduction of Kotlin and its built-in support for coroutines, Android developers now have a powerful and concise way to manage asynchronous operations. In this article, we will explore coroutines in Android using Kotlin and demonstrate their usage through practical examples.</p><p>What are Coroutines?<br>Coroutines are a feature of Kotlin that allow developers to write asynchronous code in a more sequential and readable manner. They provide the illusion of sequential execution while actually running asynchronously. Unlike traditional threads, coroutines are lightweight and more efficient, reducing the risk of memory leaks and race conditions.</p><p>Setting up Coroutines in Android:<br>To use coroutines in your Android project, you need to include the following dependencies in your app-level build.gradle file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqDUY3V2mcwF5Q4ZgCDcNg.png" /></figure><h3>Basic Usage of Coroutines:</h3><h4>1. Launching a Coroutine:</h4><p>To start a coroutine, you can use the `launch` function, which creates a new coroutine that runs on the main thread by default:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwwjmxsrELxa_LOLEbuZCw.png" /></figure><h4>2. Asynchronous Work:</h4><p>Coroutines can be used to perform time-consuming operations without blocking the main thread. For instance, making a network request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPfmZ2VbMGWqpDtVev9VVw.png" /></figure><p>In the above example, the `makeNetworkRequest` function is a suspend function. It can only be called from within a coroutine or another suspend function. The `Dispatchers.IO` specifies that the coroutine should run on the IO thread, suitable for network operations. After fetching the data, we switch back to the main thread using `Dispatchers.Main` to update the UI safely.</p><h4>3. Error Handling:</h4><p>Coroutines have built-in support for handling exceptions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDz_m3qvTiqgSa-hvfKW2A.png" /></figure><h4>4. Waiting for Multiple Coroutines:</h4><p>You can use `async` to perform multiple tasks concurrently and `await` to wait for their results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5fKIRNgKf7YnVdcI45xvw.png" /></figure><p>Thanks for reading…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c54009f0037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Printing Room DB queries in logcat]]></title>
            <link>https://arjun30.medium.com/printing-room-db-queries-in-logcat-82730e5133db?source=rss-dfeb2694285f------2</link>
            <guid isPermaLink="false">https://medium.com/p/82730e5133db</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Thu, 01 Sep 2022 12:14:12 GMT</pubDate>
            <atom:updated>2022-09-01T12:14:12.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aq_K9xeBLdf9ZdXrDC4XVw.jpeg" /></figure><p>Few weeks ago, i had written a query to do the sum of a column using SUM in query. Query was correct but i was always getting the results as 0. I checked table in DB and 13 records were present but still getting result as 0 in logcat</p><p>Using App inspection in Android Studio, i run queries and i was getting the correct value but why i was getting 0 while performing the same operation in App.</p><p>Query</p><pre><strong>@Query(&quot;SELECT sum(quiz_duration) as duration FROM quiz_details WHERE quiz_id = :quizId&quot;)<br>fun getTotalDuration(quizId: Int): Int</strong></pre><p>I was an idiot and i didn’t check the query id which i was passing to the function. In app, i was passing quizId as -1 ( Due to some issues with the state of variable and i was unaware of this) and getting results as 0 but on Android Inspection window for DB, i was passing the value as 32 thats why i was getting correct value.</p><p>After a lot of frustration and late night coding, i decide to print all my SQL queries to see queries in plain text.</p><pre>fun getInstance(context: Context): DiqueryDatabase {<br>    if (instance == null) {<br>        instance = Room.databaseBuilder(<br>            context.<em>applicationContext</em>,<br>            DiqueryDatabase::class.<em>java</em>, dbName<br>        )<strong>.setQueryCallback(RoomDatabase.QueryCallback { sqlQuery, bindArgs -&gt;<br>            <em>println</em>(&quot;SQL Query: $sqlQuery SQL Args: $bindArgs&quot;)<br>        }, Executors.newSingleThreadExecutor())</strong><br><br>            .fallbackToDestructiveMigration()<br>            .build()<br>    }<br>    return instance!!<br>}</pre><p>You can see that i have added the code to print the query inside the getInstance method of the Room Database class.</p><p>Cheers !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82730e5133db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visibility Modifiers in Kotlin]]></title>
            <link>https://arjun30.medium.com/visibility-modifiers-in-kotlin-4da850edcd76?source=rss-dfeb2694285f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4da850edcd76</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[visibility-modifier]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 07:13:29 GMT</pubDate>
            <atom:updated>2020-11-27T07:13:29.669Z</atom:updated>
            <content:encoded><![CDATA[<p>The definition of the word “modify” is to change or alter something so we can say that using Visibility modifiers we are going to change or alter the visibility of something.</p><p>Visibility modifiers are keywords that explain the visibility of Classes, objects, interface, functions, getters in Kotlin.</p><p>In Kotlin, There are 4 visibility modifiers.</p><ol><li><strong>Private</strong></li><li><strong>Protected</strong></li><li><strong>Public</strong></li><li><strong>Internal</strong></li></ol><p><strong>Private</strong></p><ul><li>Private members and methods are accessible within the class itself.</li><li>If a class primary constructor is private, You cant create an object of that class from another class.</li></ul><p><strong>Protected</strong></p><ul><li>Protected members and methods are accessible to the class within which it was declared and to the <strong>subclass</strong> of that particular class.</li><li>You cant use the <strong>Protected</strong> modifier for <strong>top-level declaration</strong>.</li></ul><p><strong>Public</strong></p><p>As the name suggests, It will be accessible to everyone. In Kotlin, the default visibility modifier is used as Public if there is no explicit modifier.</p><p><strong>Internal</strong></p><ul><li>Internal modifiers are available within the same module.</li><li>If your project has 2 modules named moduleA and moduleB so any class declared as internal will be not accessible from moduleB.</li></ul><p><strong>Note:</strong></p><p>Java doesn&#39;t support the internal visibility modifiers so when your Kotlin code gets converted into Java that time <strong>Private</strong>, <strong>Protected,</strong> and <strong>Public</strong> modifiers are kept as the same but internal modifiers are saved as <strong>Public</strong>.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4da850edcd76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manually adding local library project to ReactNative app]]></title>
            <link>https://arjun30.medium.com/manually-adding-local-library-project-to-reactnative-app-711818dafb79?source=rss-dfeb2694285f------2</link>
            <guid isPermaLink="false">https://medium.com/p/711818dafb79</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Tue, 04 Aug 2020 06:27:58 GMT</pubDate>
            <atom:updated>2020-08-04T06:27:58.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgqenn2MhgRaSR9eNJh1Yg.jpeg" /></figure><p>I was working on a native module to access some native android functionality. After development is done, I wanted to add it as a local dependency to check my module is working or not before publishing it to npm.</p><p>You can achieve this by following the below steps.</p><p><strong><em>$ npm install — save &lt;path to Library&gt;</em></strong></p><p>you need to put your local module path in place of <em>&lt;path to Library&gt;</em></p><p><strong>eg: <em>$ npm install — save /home/user/BluetoothLibrary</em></strong></p><p>After adding your module, you need to link the module.</p><p><strong><em>$ react-native link &lt;module name created in node module&gt;</em></strong></p><p><strong><em>eg: $ react-native link react-native-bluetooth</em></strong></p><p><strong>Note: </strong>You can find the module name in the <strong><em>package.json </em></strong>file.</p><p>Now run your application and you can access your module in your react-native application.</p><p>Note: If you are getting the error “module not found”, we need to delete the module folder <strong>(<em>react-native-bluetooth)</em></strong><em> </em>from node-modules and we will create a new folder with the same name <strong>(<em>react-native-bluetooth)</em></strong> inside the node-modules folder and copy-paste our original module code into that folder.</p><p>Cheers!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=711818dafb79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AlarmManager in Android]]></title>
            <link>https://arjun30.medium.com/alarmmanager-in-android-c5828db39d86?source=rss-dfeb2694285f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5828db39d86</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[alarmmanager]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 11:32:51 GMT</pubDate>
            <atom:updated>2020-06-13T11:32:51.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdxGsI1xfkNnEyIFQEf-EA.jpeg" /></figure><p>As the name suggests, Managing Alarm by using functionality provided by AlarmManager. An alarm can be set to remind us about something which is going to happen in the future and we can set alarm based on different criteria.</p><p>In Android. AlarmManager is a class that provides access to system alarm services. Using AlarmManager we can wake up our device if it&#39;s sleeping to perform some operations. In this post, just to demonstrate how to use AlarmManager I will create a sample application that will fetch data from an API and will trigger a local notification to show you the details.</p><p>So let&#39;s get started.</p><p>I will create a single Alarm that will get triggered on the launch of the application after 15 mins and when the alarm will fire it will invoke registered Broadcast which was attached with the alarm then it will start the corresponding service and trigger a local notification.</p><p>Below is our BroadcastReceiver that will invoke the service.</p><pre>public class AlarmBroadcastReceiver extends BroadcastReceiver <em>{<br><br>    </em>@Override<br>    public void onReceive<em>(</em>Context context, Intent intent<em>) { <br></em><br>        Intent serviceIntent = new Intent<em>(</em>context,    BackgroundIntentService.class<em>)</em>;<br>        context.startService<em>(</em>serviceIntent<em>)</em>;<br>    <em>}<br>}</em></pre><p>Service class to perform background tasks and generate a local notification.</p><pre>public class BackgroundIntentService extends IntentService {</pre><pre>public BackgroundIntentService(String name) {<br>        super(&quot;BackgroundIntentService&quot;);<br>    }</pre><pre>public BackgroundIntentService() {<br>        super(&quot;BackgroundIntentService&quot;);<br>    }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    protected void onHandleIntent(<a href="http://twitter.com/Nullable">@Nullable</a> Intent intent) {<br>        Log.e(&quot;Service&quot;, &quot;service called&quot;);</pre><pre>SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;EEE, d MMM yyyy, HH:mm&quot;);<br>        String dateTime = dateFormat.format(Calendar.getInstance().getTime());</pre><pre>// You can perform background task over here</pre><pre>// Generate Local Notification<br>        CommonUtils.generateLocalNotification(this, &quot;Local Notification : &quot; + dateTime+&quot; : &quot;+minutes);</pre><pre>AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);<br>        Intent alarmIntent = new Intent(this, AlarmBroadcastReceiver.class);<br>        alarmIntent.setPackage(this.getPackageName());<br>        PendingIntent alarmServicePendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);</pre><pre>if (alarmManager != null) {</pre><pre>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {<br>                alarmManager.setExactAndAllowWhileIdle(<br>                        AlarmManager.RTC,<br>                        System.currentTimeMillis() + 2 * 60 * 60 * 1000,<br>                        alarmServicePendingIntent<br>                );<br>            } else {<br>                alarmManager.set(<br>                        AlarmManager.RTC,<br>                        System.currentTimeMillis() + 2 * 60 * 60 * 1000,<br>                        alarmServicePendingIntent<br>                );<br>            }</pre><pre>}<br>    }<br>}</pre><p>I have tried to create a recurring alarm where the alarm will fire after every 2 hours and will do the background work and after that, it will set another alarm to fire after 2 hours.</p><p>To generate a local notification, you can use the below method.</p><pre>public static void generateLocalNotification<em>(</em>Context context, String title, String message<em>) {<br><br><br>    </em>String name = &quot;NotificationCN&quot;;<br>    String descriptionText = &quot;Sending Local Notification&quot;;<br>    String channelId = &quot;NotificationID&quot;;<br>    int importance = NotificationManager.<em>IMPORTANCE_HIGH</em>;<br><br><br>    Uri defaultSoundUri = RingtoneManager.<em>getDefaultUri(</em>RingtoneManager.<em>TYPE_NOTIFICATION)</em>;<br>    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder<em>(</em>context, channelId<em>)<br>            </em>.setColor<em>(</em>ContextCompat.<em>getColor(</em>context, R.color.notifictaion_icon_color<em>))<br>            </em>.setSmallIcon<em>(</em>android.R.drawable.<em>sym_def_app_icon)<br>            </em>.setContentTitle<em>(</em>title<em>)<br>            </em>.setStyle<em>(</em>new NotificationCompat.BigTextStyle<em>()<br>                    </em>.bigText<em>(</em>message<em>))<br>            </em>.setContentText<em>(</em>message<em>)<br>            </em>.setAutoCancel<em>(</em>true<em>)<br>            </em>.setPriority<em>(</em>NotificationCompat.<em>PRIORITY_HIGH)<br>            </em>.setSound<em>(</em>defaultSoundUri<em>)</em>;<br><br>    NotificationManager notificationManager =<br>            <em>(</em>NotificationManager<em>) </em>context.getSystemService<em>(</em>Context.<em>NOTIFICATION_SERVICE)</em>;<br><br>    // Since android Oreo notification channel is needed.<br>    if <em>(</em>Build.VERSION.<em>SDK_INT </em>&gt;= Build.VERSION_CODES.<em>O) {<br>        </em>NotificationChannel channel = new NotificationChannel<em>(<br>                </em>channelId,<br>                name,<br>                NotificationManager.<em>IMPORTANCE_HIGH<br>        )</em>;<br>        notificationManager.createNotificationChannel<em>(</em>channel<em>)</em>;<br>    <em>}<br><br>    </em>notificationManager.notify<em>(</em>new Random<em>()</em>.nextInt<em>()</em>, notificationBuilder.build<em>())</em>;<br><em>}</em></pre><p>You also need to register your BroadcastReceiver and Intent service inside the AndroidManifest file within the application tag.</p><pre><em>&lt;</em>service<br>    android:name=&quot;.BackgroundIntentService&quot;<br>    android:exported=&quot;false&quot; <em>/&gt;</em></pre><pre><em>&lt;</em>receiver<br>    android:name=&quot;.AlarmBroadcastReceiver&quot;<br>    android:exported=&quot;false&quot; <em>/&gt;</em></pre><p>finally, you need to set the initial alarm inside the activity.</p><pre>private void createAlarmScheduler(Context context) {<br>    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);<br>    Intent alarmIntent = new Intent(context, AlarmBroadcastReceiver.class);<br>    alarmIntent.setPackage(context.getPackageName());<br>    PendingIntent alarmServicePendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);<br>    if (alarmManager != null) {<br><br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {<br>            alarmManager.setExactAndAllowWhileIdle(<br>                    AlarmManager.RTC_WAKEUP,<br>                    System.currentTimeMillis() + 2 * 60 * 1000,<br>                    alarmServicePendingIntent<br>            );<br>          <br>        } else {<br>            alarmManager.set(<br>                    AlarmManager.RTC_WAKEUP,<br>                    System.currentTimeMillis() + 2 * 60 * 1000,<br>                    alarmServicePendingIntent<br>            );<br>           <br>        }<br>    }<br>}</pre><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5828db39d86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Workmanager Nightmare: Deleting a scheduled worker]]></title>
            <link>https://arjun30.medium.com/workmanager-nightmare-deleting-a-scheduled-worker-a5783a7bf5ca?source=rss-dfeb2694285f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5783a7bf5ca</guid>
            <category><![CDATA[workmanager]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Tue, 26 May 2020 13:55:22 GMT</pubDate>
            <atom:updated>2020-05-26T13:55:22.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlKkRLg7VuZKeiqnG146fg.jpeg" /></figure><p>We are using Workmanager to perform Network and background data sync task in our application and as per our regular code review sessions, we found that we can refactor and rewrite code so we don’t need one worker in our app.</p><p>After deleting the worker, we installed the fresh application and tested and everything was working fine. One day, our crash monitoring and reporting team told us that there is a crash reported on Google play console related to the <strong>“Class not found for com.xxxx.xxxx.BackgroundDbSyncWorker”</strong> in our application.</p><p>After testing and debugging, we found that it was happening for the worker which we have deleted in the release worker. Since. it was a periodic worker which was set to perform background sync after every 24 hours so entry for this task was present inside the <strong>Workmanager</strong> DB and when all constraint matched <a href="https://developer.android.com/reference/androidx/work/WorkerFactory"><strong>Workerfactory</strong></a> tried to instantiate the instance of the <strong>“com.xxxx.xxxx.BackgroundDbSyncWorker”</strong> but it didn’t found the <strong>BackgroundDbSyncWorker </strong>in our application so it threw Class not found an exception.</p><p>Default Worker factory will handle this scenario very well without crashing the Job but we were using custom worker factory for worker creation.</p><p>Sample of our Custom worker factory implementation:</p><pre>class DMWorkerFactory : WorkerFactory() {</pre><pre>    override fun createWorker(appContext: Context, workerClassName: String, workerParameters:<br>    WorkerParameters): ListenableWorker? {<br>    val workerClass =      Class.forName(workerClassName).asSubclass(ListenableWorker::class.java)<br>        val constructor = workerClass.getDeclaredConstructor(Context::class.java, WorkerParameters::class.java)</pre><pre>        return constructor.newInstance(appContext, workerParameters)<br>    }<br>}</pre><p>In our above sample code, <strong>“com.xxxx.xxxx.BackgroundDbSyncWorker” </strong>will be passed to the createWorker method as workerClassName parameter but the implementation of <strong>“com.xxxx.xxxx.BackgroundDbSyncWorker”</strong> class will not exist in our application so it will throw Class not found an exception.</p><p>To overcome this issue, we must handle this scenario inside the catch block and must return null as per the google docs.</p><pre>class DMWorkerFactory : WorkerFactory() {<br>    <br>    override fun createWorker(appContext: Context, workerClassName: String, workerParameters: WorkerParameters): ListenableWorker? {<br>        try {<br>            val workerClass = Class.forName(workerClassName).asSubclass(ListenableWorker::class.java)<br>            val constructor = workerClass.getDeclaredConstructor(Context::class.java, WorkerParameters::class.java)<br>            return constructor.newInstance(appContext, workerParameters)<br>        } catch (e: ClassNotFoundException) {<br>            return null<br>        }<br>    }<br>}</pre><p>Thanks for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5783a7bf5ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Notification in Android]]></title>
            <link>https://arjun30.medium.com/simple-notification-in-android-6bf19c7ece39?source=rss-dfeb2694285f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bf19c7ece39</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[firebasecloudmessaging]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[notifications]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Tue, 26 May 2020 02:59:48 GMT</pubDate>
            <atom:updated>2020-05-26T03:02:04.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iS1-YAHhIFxwHAPk4Ps6rg.jpeg" /></figure><p>Notifications are a way to provide information to your customer which displays as a pop up on the device. It helps you to keep in touch with your customer.</p><p>I am going to create a simple notification without going deep because everything is available on Google.</p><p>We must understand a few concepts before going further.</p><p><strong>Notification channel: </strong>Assume you have developed an app for an online learning center where they teach Maths and English. Students can either learn Maths, English, or Both. we must send notification related to Maths to only students who have taken Maths. In this case, we can create channels for Maths, English, and both so triggered notification will be delivered to students who have taken that subject.</p><p>Each Notification channel can have a different Notification sound and different behavior that you can change from the Notification setting page. I forgot to tell you that Google has introduced the Notification channel from Android 8.0 i.e API level 26. Now you might be thinking that I just have to show a simple notification so you have to create a default Notification channel.</p><pre>val name = &quot;NotificationCN&quot; // Channel Name visible to user<br>val descriptionText = &quot;Sending Notification&quot;<br>val channelId = &quot;NotificationID&quot;<br>val importance = NotificationManager.<em>IMPORTANCE_HIGH // Notification Priority<br><br><br></em>val defaultSoundUri = RingtoneManager.getDefaultUri<em>(</em>RingtoneManager.<em>TYPE_NOTIFICATION)<br></em>val notificationBuilder = NotificationCompat.Builder<em>(</em>context, channelId<em>)<br>    </em>.setColor<em>(</em>ContextCompat.getColor<em>(</em>context, android.R.color.<em>holo_red_dark))<br>    </em>.setSmallIcon<em>(</em>android.R.drawable.<em>sym_def_app_icon)<br>    </em>.setContentTitle<em>(</em>title<em>)<br>    </em>.setContentText<em>(</em>message<em>)<br>    </em>.setAutoCancel<em>(</em>true<em>)<br>    </em>.setPriority<em>(</em>NotificationCompat.<em>PRIORITY_HIGH)<br>    </em>.setSound<em>(</em>defaultSoundUri<em>)<br><br></em>val notificationManager =<br>    context.getSystemService<em>(</em>Context.<em>NOTIFICATION_SERVICE) </em>as NotificationManager<br><br>// Since android Oreo notification channel is needed.<br>if <em>(</em>Build.VERSION.<em>SDK_INT </em>&gt;= Build.VERSION_CODES.<em>O) {<br>    </em>val channel = NotificationChannel<em>(<br>        </em>channelId,<br>        name,<br>        NotificationManager.<em>IMPORTANCE_HIGH<br>    )<br>    </em>notificationManager.createNotificationChannel<em>(</em>channel<em>)<br>}<br><br></em>notificationManager.notify<em>(</em>Random.nextInt<em>()</em>,notificationBuilder.buid<em>())</em></pre><p>I hope you will find it useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bf19c7ece39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webview data directory for Android 9 (Pie)]]></title>
            <link>https://arjun30.medium.com/webview-data-directory-for-android-9-pie-d9744a1404e9?source=rss-dfeb2694285f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9744a1404e9</guid>
            <category><![CDATA[webview-app-builder]]></category>
            <category><![CDATA[android-pie]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Sat, 06 Jul 2019 15:30:44 GMT</pubDate>
            <atom:updated>2019-07-06T15:30:44.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TWW_kmC28W_rfXJqT6oPg.jpeg" /></figure><p>From Crashlytics report, i got to know that my app is crashing on Android 9 devices. After checking stacktrace log, it was related to data directory of webview running in multiprocess . Webview data directory store cookies, HTTP caches, and other persistent and temporary storage related to web browsing.</p><pre>java.lang.IllegalStateException: Can&#39;t set data directory suffix: WebView already initialized</pre><p>After reading Google documentation, It was clear that from android 9 webview running in multiprocess can not share same data directory so we have to make sure that webview in each process must have it’s own data directory which we can set by calling Webview.setDataDirectorySuffix().</p><p>To fix this issue, I have updated my application to check if my current process is other then my main process so i will set data directory to webview. By default, applications component run in a single <a href="https://developer.android.com/guide/components/processes-and-a">process</a> until and unless you run component in another <a href="https://developer.android.com/guide/components/processes-and-a">process</a>. You can specify the process in which your component should run by <strong>android:process </strong>tag.</p><p>Below is the code to check the process and assign data directory to webview.</p><pre>package com.arjun.webviewdemo;<br><br>import android.app.ActivityManager;<br>import android.app.Application;<br>import android.content.Context;<br>import android.os.Build;<br>import android.webkit.WebView;<br><br>public class MyApplication extends Application {<br><br>    @Override<br>    public void onCreate() {<br>        super.onCreate();<br><br>        if (Build.VERSION.<em>SDK_INT </em>&gt;= Build.VERSION_CODES.<em>P</em>) {<br><br>            String processName = getProcessName(this);<br>            if (!&quot;com.arjun.webviewdemo&quot;.equals(processName)) {<br>                WebView.<em>setDataDirectorySuffix</em>(processName);<br>            }<br>        }<br><br><br>    }<br><br>    public String getProcessName(Context context) {<br>        if (context == null) return null;<br>        ActivityManager manager = (ActivityManager) context.getSystemService(Context.<em>ACTIVITY_SERVICE</em>);<br>        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {<br>            if (processInfo.pid == android.os.Process.<em>myPid</em>()) {<br>                return processInfo.processName;<br>            }<br>        }<br>        return null;<br>    }<br>}</pre><p>Cheers !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9744a1404e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Push Notification using FCM for Titanium]]></title>
            <link>https://arjun30.medium.com/android-push-notification-using-fcm-for-titanium-8f7f325096f8?source=rss-dfeb2694285f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7f325096f8</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[titanium]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[firebasecloudmessaging]]></category>
            <dc:creator><![CDATA[Arjun Singh]]></dc:creator>
            <pubDate>Fri, 21 Sep 2018 20:18:21 GMT</pubDate>
            <atom:updated>2018-09-22T05:36:36.421Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I am going to integrate the push notification in my Titanium app using the FCM module provide by the <a href="https://github.com/hansemannn/titanium-firebase-cloud-messaging">Hans ( hansemannn)</a> . I have used another module for FCM but that was not working on devices running Oreo and i was looking for other modules and i came across this module and it was working fine on Oreo devices and it also provides me option to customise the notifications also.</p><h3>Integrating FCM</h3><p>Assuming that you are familiar with Firebase cloud messaging, I am going to create a new project in the Firebase console. you can go to the Firebase console by using this <a href="https://console.firebase.google.com/">URL</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*XdfeIPJciRQNCYVq.png" /></figure><p>you have to click on Add project to create a new Firebase project then it will open a pop up box where you can enter the details of your new app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*jgGARcxgNnvuaU_l.png" /></figure><p>I have entered app name as NotificationDemo1 and you can also add Firebase to your existing app by selecting it from the dropdown menu and you have to select the two checkboxes and click on create project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ER5bUVvJ29PfgvgJ.png" /></figure><p>We are doing it for Android so we have to click on Android icon and then we will get the option to register our app on the Firebase where we have to provide information of package name of our Android app, App nickname ( optional ) and Debug Signing Certificate SHA-1 ( optional) and you have to register you application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Tf6VhjDtYRFy56Xx.png" /></figure><p>You have to click on register app and then you have to download the google-services.json file which contains project-id’s and tracking-id’s and such, generated by the Google API developer console into the google-services.json file. You have to click the next button for the the rest of process and when you came to step 4 then you have to “Run your app to verify installation” click the skip this steps button and Now, we have successfully completed the firebase project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*KP2d1fdef4yWyZyg.png" /></figure><h3>Titanium Integration</h3><p>We will add the firebase.cloudmessaging, firebase.core and ti.playservices modules to our tiapp.xml file. you can read more about this module over <a href="https://github.com/hansemannn/titanium-firebase">here</a>. We also have to add the google-services.json file to our assets/android folder which will picked up by the module for information related to the firebase app. You will get your token inside the console window.</p><h3>Index.js</h3><pre>// Configure core module (required for all Firebase modules).<br>var core = require(&#39;firebase.core&#39;);<br>core.configure({<br> file : &quot;google-services.json&quot;<br>});<br>var fcm = require(&#39;firebase.cloudmessaging&#39;);</pre><pre>function registerAndroid() {<br> // Called when the Firebase token is registered or refreshed.<br> fcm.addEventListener(&#39;didRefreshRegistrationToken&#39;, function(e) {<br>  Ti.API.info(&#39;Token&#39;, e.fcmToken);<br>  Ti.App.Properties.setString(&#39;push_token&#39;, e.fcmToken);<br> });</pre><pre> // Called when direct messages arrive. Note that these are different from push notifications.<br> fcm.addEventListener(&#39;didReceiveMessage&#39;, function(e) {<br>  Ti.API.info(&#39;Message&#39;, e.message);<br> });</pre><pre> // Register the device with the FCM service.<br> fcm.registerForPushNotifications();</pre><pre> // Check if token is already available.<br> if (fcm.fcmToken) {<br>  Ti.API.info(&#39;FCM-Token&#39;, fcm.fcmToken);<br>  Ti.App.Properties.setString(&#39;push_token&#39;, fcm.fcmToken);</pre><pre> } else {<br>  Ti.API.info(&#39;Token is empty. Waiting for the token callback ...&#39;);<br> }<br>}</pre><pre>registerAndroid();</pre><pre>$.index.open();</pre><h3>tiapp.xml</h3><pre>&lt;modules&gt;<br>        &lt;module platform=&quot;android&quot;&gt;firebase.cloudmessaging&lt;/module&gt;<br>        &lt;module platform=&quot;android&quot;&gt;firebase.core&lt;/module&gt;<br>        &lt;module platform=&quot;android&quot;&gt;ti.playservices&lt;/module&gt;<br>    &lt;/modules&gt;</pre><h3>Postman</h3><p>I have used postman to send data message . You have to copy Legacy Server Key from <strong>Firebase console &gt; Project Settings &gt; Cloud Messaging</strong></p><p>You have to add below header to your Post request.</p><p><strong>Authorization : Key=&lt;Legacy_server_key&gt; or Key=&lt;server_key&gt;</strong></p><p><strong>Content-Type: application/json</strong></p><p>You have to copy the device token from the console window and you have to paste it inside the registration_ids array inside the body of post request. If you wanted to send notification to more then one devices then token should be comma separated inside the registration_ids field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*rPqHTOVTXFGJ9yQs.png" /></figure><p>you can import the postman collection from this <a href="https://www.getpostman.com/collections/5950b7fb8fdb2854855f">link</a>.</p><p>This is how it will look in the device when you trigger the notification from postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*Jx8XxME0vlZqWIxy.png" /></figure><p>Cheers !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7f325096f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>