<?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 G. Raj Kumar on Medium]]></title>
        <description><![CDATA[Stories by G. Raj Kumar on Medium]]></description>
        <link>https://medium.com/@raj2512flair?source=rss-af4dc8a044ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4y7F9P_TIdKs_l02v0ohig.jpeg</url>
            <title>Stories by G. Raj Kumar on Medium</title>
            <link>https://medium.com/@raj2512flair?source=rss-af4dc8a044ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:31:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raj2512flair/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[Effortlessly Save and Manage User Data in Android: Using DataStore with Kotlin Data Classes]]></title>
            <link>https://medium.com/@raj2512flair/effortlessly-save-and-manage-user-data-in-android-using-datastore-with-kotlin-data-classes-c10e95141bbb?source=rss-af4dc8a044ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/c10e95141bbb</guid>
            <category><![CDATA[kotlin-data-class]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[jetpack-datastore]]></category>
            <dc:creator><![CDATA[G. Raj Kumar]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 17:08:28 GMT</pubDate>
            <atom:updated>2024-12-29T17:08:28.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CJRtyuGKUBDYErk5" /><figcaption>Photo by <a href="https://unsplash.com/@wacalke?utm_source=medium&amp;utm_medium=referral">Mateusz Wacławek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous <strong><em>blog</em></strong>, I explored how to save data using Preference DataStore in Android applications. The Preference DataStore, akin to SharedPreferences, enables key-value pair data storage. However, when dealing with more complex data, such as a user profile shared across multiple screens in an app, the key-value approach can become cumbersome. Managing consistency and handling reads/writes effectively can be challenging.</p><p>To address these challenges, this tutorial demonstrates a hassle-free method leveraging Kotlin data classes and Kotlin Serialization to store data as JSON in DataStore. Let’s dive in!</p><h3>Implementation:</h3><p><strong>Add Dependencies</strong></p><p>First, set up your Gradle dependencies by adding the following lines to your libs.versions.toml file:</p><pre>[versions]<br>kotlinxSerializationJson = &quot;1.6.3&quot;  <br>kotlinxSerialization = &quot;1.9.23&quot;<br>datastorePreferences = &quot;1.1.1&quot;<br><br>[libraries]<br>kotlinx-serialization-json = { module = &quot;org.jetbrains.kotlinx:kotlinx-serialization-json&quot;, version.ref = &quot;kotlinxSerializationJson&quot; }<br>androidx-datastore-preferences = { module = &quot;androidx.datastore:datastore-preferences&quot;, version.ref = &quot;datastorePreferences&quot; }<br><br>[plugins]<br>jetbrains-kotlin-serialization = { id = &quot;org.jetbrains.kotlin.plugin.serialization&quot;, version.ref = &quot;kotlinxSerialization&quot; }</pre><p>Then, import them into your app module’s build.gradle.kts file:</p><pre>plugins {<br>    alias(libs.plugins.jetbrains.kotlin.serialization)<br>}<br><br>dependencies {<br>    implementation(libs.kotlinx.serialization.json)<br>    implementation(libs.androidx.datastore.preferences)<br>}</pre><p><strong>Note:</strong> This tutorial assumes your project already includes Kotlin Coroutines dependencies.</p><h3>Getting Started:</h3><h4><strong>Immutable Data Classes</strong></h4><p>DataStore is designed to work with immutable data types to avoid issues like data inconsistency and race conditions, making the use of primitive data types makes a data class immutable. Therefore, avoid mutable collections like Array or List. Instead, use persistent collections.</p><p>Here’s a sample immutable data class for a user profile:</p><pre>@Serializable  <br>data class UserProfilePreferences(  <br>    val id: String = &quot;&quot;,  <br>    val displayName: String = &quot;&quot;,  <br>    val firstName: String = &quot;&quot;,  <br>    val lastName: String = &quot;&quot;,  <br>    val email: String = &quot;&quot;,  <br>    val phone: String = &quot;&quot;,  <br>    val avatar: String = &quot;&quot;  <br>)</pre><h4><strong>Kotlin Serialization with DataStore</strong></h4><p>Preference DataStore relies on the Preferences API, which includes PreferencesSerializer for low-level operations. This enables data to be stored efficiently using Protobuf, for more details you can refer to this <a href="https://medium.com/androiddevelopers/datastore-and-kotlin-serialization-8b25bf0be66c"><strong><em>link</em></strong></a>. In this tutorial, we’ll create a custom serializer to handle JSON serialization for user profiles.</p><h4><strong>Custom Serializer</strong></h4><p>Here’s the implementation of a serializer for UserProfilePreferences:</p><pre>import androidx.datastore.core.CorruptionException  <br>import androidx.datastore.core.Serializer  <br>import com.app.example.UserProfilePreferences  <br>import kotlinx.coroutines.Dispatchers  <br>import kotlinx.coroutines.withContext  <br>import kotlinx.serialization.SerializationException  <br>import kotlinx.serialization.json.Json  <br>import java.io.InputStream  <br>import java.io.OutputStream  <br>  <br>object UserProfilePreferenceSerializer : Serializer&lt;UserProfilePreferences&gt; {  <br>    override val defaultValue: UserProfilePreferences = UserProfilePreferences()  <br>  <br>    override suspend fun readFrom(input: InputStream): UserProfilePreferences {  <br>        try {  <br>            return Json.decodeFromString(  <br>                deserializer = UserProfilePreferences.serializer(),  <br>                string = input.readBytes().decodeToString()  <br>            )  <br>        } catch (e: SerializationException) {  <br>            throw CorruptionException(&quot;Unable to read UserProfilePreferences&quot;, e)  <br>        }  <br>    }  <br>  <br>    override suspend fun writeTo(t: UserProfilePreferences, output: OutputStream) =  <br>        withContext(Dispatchers.IO) {  <br>            output.write(  <br>                Json.encodeToString(  <br>                    serializer = UserProfilePreferences.serializer(),  <br>                    value = t  <br>                ).encodeToByteArray()  <br>            )  <br>        }  <br>}</pre><h4>Dependency Injection Setup</h4><p>To ensure proper instantiation and usage, let’s set up dependency injection using Hilt. The following code defines the necessary module for providing DataStore as a singleton:</p><pre>private const val DATASTORE_FILE_NAME = &quot;user_profile_prefs.json&quot;<br><br>@Module  <br>@InstallIn(SingletonComponent::class)  <br>object PersistenceModule {  <br><br>    @Provides  <br>    @Singleton  <br>    fun provideDataStore(@ApplicationContext appContext: Context): DataStore&lt;UserProfilePreferences&gt; {  <br>        return DataStoreFactory.create(  <br>            serializer = UserProfilePreferenceSerializer,  <br>            corruptionHandler = ReplaceFileCorruptionHandler(produceNewData = {  <br>                UserProfilePreferences()  <br>            }),  <br>            scope = CoroutineScope(Dispatchers.IO + SupervisorJob()),  <br>            produceFile = { appContext.dataStoreFile(DATASTORE_FILE_NAME) }  <br>        )  <br>    }  <br><br>    @Provides  <br>    @Singleton  <br>    fun provideUserProfileRepository(  <br>        dataStore: DataStore&lt;UserProfilePreferences&gt;  <br>    ): UserProfileRepository {  <br>        return UserProfileRepositoryImpl(dataStore)  <br>    }  <br>}</pre><h4>Data Handling and Repository Implementation</h4><p>To manage updates and retrieval of data from DataStore effectively, we define an interface and provide a concrete implementation for the business logic.</p><h4>UserProfileRepository Interface</h4><p>The UserProfileRepository interface defines the contract for data operations, including observing changes to the user profile and updating specific data fields:</p><pre>interface UserProfileRepository {  <br>    // Observes changes in the user profile data.<br>    val userProfileFlow: StateFlow&lt;UserProfilePreferences&gt;  <br>  <br>    // Updates user data with a new User object from a remote API.<br>    suspend fun updateUserData(user: User)  <br>  <br>    // Updates only the avatar URL of the user profile.<br>    suspend fun updateAvatarUrl(url: String)   <br>}</pre><h4>Data Retrieval and Updates</h4><p>To interact with the DataStore, use the dataStore.data.collect { ... } method to retrieve data and dataStore.updateData { ... } to modify it. The implementation ensures that updates are seamless and changes to the user profile are emitted to observers.</p><p>Here’s the complete implementation of the repository class:</p><pre>import android.util.Log  <br>import androidx.datastore.core.DataStore  <br>import com.app.example.UserProfilePreferences  <br>import com.app.example.remote.model.response.User  <br>import kotlinx.coroutines.flow.MutableStateFlow  <br>import kotlinx.coroutines.flow.StateFlow  <br>import kotlinx.coroutines.flow.asStateFlow  <br>import kotlinx.coroutines.launch  <br>import kotlinx.serialization.SerializationException  <br>import java.io.IOException  <br>import javax.inject.Inject  <br>  <br>class UserProfileRepositoryImpl @Inject constructor(  <br>    private val dataStore: DataStore&lt;UserProfilePreferences&gt;  <br>) : UserProfileRepository {  <br>    private val tag = &quot;UserProfileRepository&quot;  <br>  <br>    // Backing property for the user profile flow<br>    private val _userProfileFlow = MutableStateFlow(UserProfilePreferences())  <br>    override val userProfileFlow: StateFlow&lt;UserProfilePreferences&gt;  <br>        get() = _userProfileFlow.asStateFlow()  <br>  <br>    init {  <br>        CoroutineScope(Dispatchers.IO).launch {  <br>            getUserDataFlow()  <br>        }  <br>    }  <br>  <br>    // Updates the user profile with data from a User object<br>    override suspend fun updateUserData(user: User) {  <br>        safeInvoke {  <br>            dataStore.updateData { userProfileData -&gt;  <br>                userProfileData.copy(  <br>                    id = user.userId,  <br>                    displayName = &quot;${user.firstName} ${user.lastName}&quot;,  <br>                    firstName = user.firstName,  <br>                    lastName = user.lastName,  <br>                    email = user.email,  <br>                    phone = user.phone,  <br>                    avatar = user.avatar  <br>                )  <br>            }  <br>        }  <br>    }  <br>  <br>    // Updates only the avatar URL<br>    override suspend fun updateAvatarUrl(url: String) {  <br>        safeInvoke {  <br>            dataStore.updateData { userProfileData -&gt;  <br>                userProfileData.copy(avatar = url)  <br>            }  <br>        }  <br>    }  <br>  <br>    // Fetches the user profile data and updates the state flow<br>    private suspend fun getUserDataFlow() {  <br>        safeInvoke {  <br>            dataStore.data.collect { userProfileData -&gt;  <br>                _userProfileFlow.value = userProfileData  <br>            }  <br>        }  <br>    }  <br>  <br>    // A helper function to handle exceptions during DataStore operations<br>    private inline fun &lt;T&gt; safeInvoke(execute: () -&gt; T) {  <br>        try {  <br>            execute()  <br>        } catch (e: SerializationException) {  <br>            Log.e(tag, &quot;Serialization error: ${e.localizedMessage}&quot;)  <br>        } catch (e: IOException) {  <br>            Log.e(tag, &quot;I/O error: ${e.localizedMessage}&quot;)  <br>        } catch (e: Exception) {  <br>            Log.e(tag, &quot;Unexpected error: ${e.localizedMessage}&quot;)  <br>        }  <br>    }  <br>}</pre><h3>Key Highlights</h3><ol><li><strong>Observability with StateFlow:</strong><br>The MutableStateFlow tracks and emits changes to the user profile data in real-time, ensuring the UI remains up-to-date.</li><li><strong>Safe Data Manipulation:</strong><br>The safeInvoke helper method encapsulates DataStore operations to handle exceptions like SerializationException and IOException, reducing the risk of application crashes.</li><li><strong>Seamless Updates:</strong><br>Methods like updateUserData and updateAvatarUrl simplify the process of modifying specific fields in the user profile while maintaining data integrity.</li><li><strong>Asynchronous Data Retrieval:</strong><br>The getUserDataFlow method asynchronously collects user profile data, ensuring responsiveness and non-blocking execution.</li></ol><h3>Conclusion</h3><p>In this tutorial, we explored an efficient approach to store and manage structured data in Android applications using DataStore and Kotlin Serialization. By utilizing immutable data classes, custom serializers, and robust repository patterns, you can ensure data consistency, reliability, and ease of use across your app.</p><p>Feel free to extend this implementation by incorporating additional use cases like error reporting or real-time syncing with a remote server. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c10e95141bbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhance Multilingual Support in Your Android App with Google’s ML Kit for Text Translation]]></title>
            <link>https://medium.com/@raj2512flair/enhance-multilingual-support-in-your-android-app-with-googles-ml-kit-for-text-translation-97ad69e31e1c?source=rss-af4dc8a044ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ad69e31e1c</guid>
            <category><![CDATA[translate-text]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[google-ml-kit]]></category>
            <category><![CDATA[language-translation]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[G. Raj Kumar]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 09:45:33 GMT</pubDate>
            <atom:updated>2024-11-09T09:45:33.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AVM4u1n1L5yfzOeo" /><figcaption>Photo by <a href="https://unsplash.com/@mullyadii?utm_source=medium&amp;utm_medium=referral">Mulyadi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With Android’s rapidly expanding global user base, supporting multiple languages within applications is no longer a luxury — it’s a necessity. Modern Android apps need to provide a seamless user experience across language barriers, enabling users to interact with content in their preferred language. Google’s ML Kit, an accessible machine learning toolkit, makes it remarkably straightforward to implement text translation within Android apps, broadening their usability across diverse linguistic demographics. In this tutorial, we’ll guide you step-by-step on how to integrate ML Kit’s text translation feature, ensuring that your app delivers a truly globalized experience for users around the world.</p><h4>Step 1: Configure Project Dependencies</h4><p>To get started, we’ll first add the necessary dependencies in our Gradle configuration. This guide will demonstrate how to implement the translation library using the latest libs.versions.toml approach, which simplifies version management across modules.</p><pre>[versions]<br>translate = &quot;17.0.2&quot;<br><br>[libraries]<br>translate = { module = &quot;com.google.mlkit:translate&quot;, version.ref = &quot;translate&quot; }</pre><p>Now, import this dependency into the app module’s Gradle file within the dependencies { } section:</p><pre>// Language translation library<br>implementation(libs.translate)</pre><h4>Step 2: Set Up the Translator</h4><p>With dependencies configured, we’ll create a translator instance to define the source and target languages. Here, we’ll be translating from English to Hindi, though you can easily adjust these settings for other language pairs.</p><pre>private val options = TranslatorOptions.Builder()  <br>    .setSourceLanguage(TranslateLanguage.ENGLISH)  <br>    .setTargetLanguage(TranslateLanguage.HINDI) <br>    .build()<br>private val englishHindiTranslator = Translation.getClient(options)</pre><h4>Step 3: Download the Translation Model</h4><p>To perform translations offline, the translation model needs to be downloaded first, before calling the `translate()` method with the provided text . The following function initiates the model download if it hasn’t been installed on the device yet. We use a callback here to confirm the download status, allowing us to update the UI or save the status in shared preferences as needed.</p><pre>suspend fun downloadTranslatorIfNeeded(result: (Boolean) -&gt; Unit) {  <br>    val conditions = DownloadConditions.Builder()  <br>        .requireWifi()  <br>        .build()  <br>    englishHindiTranslator.downloadModelIfNeeded(conditions)  <br>        .addOnSuccessListener {  <br>            // Model downloaded successfully, ready for translation.<br>            result(true)  <br>        }  <br>        .addOnFailureListener { exception -&gt;  <br>            // Handle download failure<br>            result(false)  <br>        }  <br>}</pre><p>The function above returns true if the model downloads successfully, or false if there’s an error. By specifying requireWifi(), we ensure the model only downloads when connected to Wi-Fi, which is ideal for preserving mobile data.</p><h4>Step 4: Translate Text</h4><p>Now that the model is available, we can proceed with translating text from English to Hindi. The following function handles the translation process and returns the translated text or null if the operation fails.</p><pre>suspend fun translateEnglishToHindi(text: String): String? {<br>    val result = callBackReducedResult(text) ?: text <br>    return result  <br>}<br><br>private suspend fun callBackReducedResult(text: String): String? {  <br>    return suspendCoroutine { continuation -&gt;  <br>        try {  <br>            englishHindiTranslator.translate(text)  <br>                .addOnSuccessListener { translatedText -&gt;  <br>                    continuation.resume(translatedText)  <br>                }  <br>                .addOnFailureListener { exception -&gt;  <br>                    exception.printStackTrace()  <br>                    continuation.resume(null)  <br>                }  <br>        } catch (e: Exception) {  <br>            continuation.resume(null)  <br>        }  <br>    }  <br>}</pre><p>In this code, we use suspendCoroutine to convert the callback-based google API into a coroutine-friendly function, keeping the code flow consistent. By calling continuation.resume() upon success or failure, we ensure the coroutine awaits the translation result without blocking a thread, maintaining responsiveness within the app.</p><h4>Step 5: Clean Up Resources</h4><p>Once you no longer need the translation service, make sure to close the translator to free up memory resources.</p><pre>fun closeTheTranslatorWhenNotInNeed() {  <br>    englishHindiTranslator.close()  <br>}</pre><h4>Conclusion:</h4><p>Integrating Google’s ML Kit for text translation opens up your Android app to a broader audience, ensuring a user-friendly experience across languages. With just a few steps, you can implement translation capabilities to cater to users worldwide, enhancing engagement and satisfaction. Embrace multilingual support and make your app a globally accessible platform.</p><p>Thank you for following this tutorial!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97ad69e31e1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Notification Listener Service in Android]]></title>
            <link>https://blog.stackademic.com/exploring-the-notification-listener-service-in-android-7db54d65eca7?source=rss-af4dc8a044ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/7db54d65eca7</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[notification-service]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[G. Raj Kumar]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 12:51:00 GMT</pubDate>
            <atom:updated>2025-08-28T06:23:59.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6NArjYkj-McspHgV" /><figcaption>Photo by <a href="https://unsplash.com/@gabrielrana?utm_source=medium&amp;utm_medium=referral">Gabriel Tovar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this guide, we’ll delve into setting up and using the NotificationListenerService, explore the permissions required, and address common issues such as service disconnection and handling permissions for various Android configurations. By the end, you&#39;ll be equipped to integrate notification listening into your app seamlessly, enabling it to listen for notifications, respond to changes, and enhance app utility for your users.</p><h4>What is Notification Listener Service?</h4><p>The NotificationListenerService is a unique service in the Android framework that allows an app to monitor notifications posted to the status bar. However, it requires explicit permissions from the user due to its sensitivity. Users must grant specific access settings before the app can listen to notifications, adding an essential layer of security. Once set up, the listener service can receive system calls whenever a new notification is posted, removed, or updated, making it a powerful tool for applications that benefit from real-time notification data.</p><h4>Key Considerations for Notification Listener Service</h4><p>Before implementing this service, it’s critical to keep a few limitations in mind:</p><ul><li><strong>Low-RAM Devices</strong>: Notification listeners do not function on low-RAM devices with Android Q and below, as the system restricts access for performance reasons.</li><li><strong>Work Profiles</strong>: Notifications generated within a work profile may not be accessible due to device policy restrictions. The DevicePolicyManager may block notifications, especially when managed by an organization.</li></ul><h4>Implementing the Notification Listener Service</h4><p>To start, ensure your app has the necessary permissions in the AndroidManifest.xml:</p><pre>&lt;uses-permission android:name=&quot;android.permission.BIND_NOTIFICATION_LISTENER_SERVICE&quot; <br>    tools:ignore=&quot;ProtectedPermissions&quot; /&gt;</pre><p>Within the &lt;application&gt; tag, add the following configuration to declare the notification listener service:</p><pre>&lt;service android:name=&quot;.NotificationListener&quot; <br>          android:label=&quot;@string/service_name&quot;<br>          android:exported=&quot;false&quot;<br>          android:permission=&quot;android.permission.BIND_NOTIFICATION_LISTENER_SERVICE&quot;&gt;<br>     &lt;intent-filter&gt;<br>         &lt;action android:name=&quot;android.service.notification.NotificationListenerService&quot; /&gt;<br>     &lt;/intent-filter&gt;<br>     &lt;meta-data<br>               android:name=&quot;android.service.notification.default_filter_types&quot;<br>               android:value=&quot;conversations|alerting&quot;&gt;<br>           &lt;/meta-data&gt;<br>     &lt;meta-data<br>               android:name=&quot;android.service.notification.disabled_filter_types&quot;<br>               android:value=&quot;ongoing|silent&quot;&gt;<br>           &lt;/meta-data&gt;<br> &lt;/service&gt;</pre><p>Replace NotificationListener with the class name you intend to use for extending NotificationListenerService.</p><h4>Developing the Notification Listener Class</h4><p>Next, create a NotificationListener class that extends NotificationListenerService. First let’s start with methods we can override to serve our usecase.</p><pre>override fun onCreate() {  <br>    super.onCreate()   <br>}</pre><p>onCreate(): This function serves as the entry point for the service, where you can execute any preliminary setup or initialization relevant to your application’s requirements. It is typically the first method invoked when the service starts, allowing developers to configure essential components or allocate resources in preparation for the service’s operations.</p><pre>private var componentName: ComponentName? = null<br><br>override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {  <br>        super.onStartCommand(intent, flags, startId)<br>        <br>        if(componentName == null) {<br>            componentName = ComponentName(this, this::class.java)<br>        }<br>        <br>        componentName?.let {  <br>            requestRebind(it)  <br>            toggleNotificationListenerService(it)  <br>        }  <br>        return START_REDELIVER_INTENT  <br>    }<br><br>private fun toggleNotificationListenerService(componentName: ComponentName) {  <br>        val pm = packageManager  <br>        pm.setComponentEnabledSetting(<br>            componentName,  <br>            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,<br>            PackageManager.DONT_KILL_APP   <br>        )  <br>        pm.setComponentEnabledSetting(<br>            componentName,  <br>            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,<br>            PackageManager.DONT_KILL_APP  <br>        )  <br>    }</pre><p>onStartCommand(): This method is triggered each time the service is started. Within this function, two key methods are invoked: requestRebind() and toggleNotificationListenerService(), both of which require a ComponentName as an argument.</p><ul><li><strong>requestRebind()</strong>: This method is employed to re-establish the binding of the notification listener, particularly after a prior call to requestUnbind(). Rebinding the listener is essential because it may sometimes become unexpectedly unbound, ceasing to listen for notifications. By requesting a rebind, we ensure the continuity of notification listening, even in cases where disconnection might otherwise occur.</li><li><strong>toggleNotificationListenerService()</strong>: Through observations, it became evident that the notification listener service occasionally stops responding to notifications, even when the required permission has been granted. After investigating possible causes, a solution was discovered on StackOverflow, suggesting that the service requires manual re-enablement by unbinding and rebinding the component. This workaround compensates for potential bugs in the notification listener, allowing it to reliably resume listening for notifications without interruption.</li><li><strong>START_REDELIVER_INTENT</strong>: This flag instructs the service to automatically restart if its process is unexpectedly terminated while it is active (that is, after it has returned from onStartCommand(). When the service is restarted, it will re-receive the last delivered Intent via onStartCommand. This flag ensures the service’s resilience, as it maintains its functionality even after unexpected terminations.</li></ul><pre>override fun onListenerConnected(){<br>     Log.d(&quot;NotificationListener&quot;,&quot;onListenerConnected&quot;)<br>     super.onListenerConnected()<br>}</pre><p>onListenerConnected(): This method indicates that the notification listener has successfully connected, thus enabling it to listen for notifications. While both onCreate() and onStartCommand() are invoked when the notification listener service starts, notifications will only begin to be received after onListenerConnected() is called. This connection occurs only once the user has granted the necessary permissions, providing a secure way to begin listening for notifications after obtaining explicit user consent.</p><pre>override fun onListenerDisconnected() {  <br>        super.onListenerDisconnected()<br>        <br>        if (componentName == null) {  <br>            componentName = ComponentName(this, this::class.java)  <br>        }  <br>        <br>        componentName?.let { requestRebind(it) }  <br>    }</pre><p>onListenerDisconnected(): This method is triggered whenever the notification listener is disconnected from the service. Upon disconnection, it is essential to rebind the listener to ensure continuous operation. By requesting a rebind within this method, the listener can be swiftly reconnected, avoiding prolonged downtimes and guaranteeing that it resumes notification monitoring at the earliest possible instance.</p><pre>override fun onNotificationPosted(sbn: StatusBarNotification?) {<br>        val packageName = sbn?.packageName ?: &quot;&quot;<br>        val extras = sbn?.notification?.extras<br>        <br>        // Extract data from notification extras as needed<br>        val title = extras?.getCharSequence(&quot;android.title&quot;).toString()<br>        val text = extras?.getCharSequence(&quot;android.text&quot;).toString()<br>    }</pre><p>onNotificationPosted(sbn: StatusBarNotification?): This function represents the core functionality of the notification listener, allowing it to read notifications as they are received. Within this function, the StatusBarNotification object (sbn) contains all vital data related to the incoming notification. For instance, this example demonstrates how to extract the packageName of the application that issued the notification, as well as the extras bundle, which holds the additional details embedded within the notification. By iterating through these key-value fields within the extras bundle, you can retrieve specific data points tailored to your requirements, enhancing the customization and responsiveness of your app’s interaction with notifications.</p><p>Here’s the basic structure of the whole class:</p><pre>class NotificationListener : NotificationListenerService() {<br>    private var componentName: ComponentName? = null<br><br>    override fun onCreate() {  <br>        super.onCreate()   <br>    }<br><br>    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {  <br>        super.onStartCommand(intent, flags, startId)<br>        <br>        if(componentName == null) {<br>            componentName = ComponentName(this, this::class.java)<br>        }<br>        <br>        componentName?.let {  <br>            requestRebind(it)  <br>            toggleNotificationListenerService(it)  <br>        }  <br>        return START_REDELIVER_INTENT  <br>    }<br><br>    private fun toggleNotificationListenerService(componentName: ComponentName) {  <br>        val pm = packageManager  <br>        pm.setComponentEnabledSetting(<br>            componentName,  <br>            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,<br>            PackageManager.DONT_KILL_APP   <br>        )  <br>        pm.setComponentEnabledSetting(<br>            componentName,  <br>            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,<br>            PackageManager.DONT_KILL_APP  <br>        )  <br>    }<br><br>    override fun onListenerConnected() {    <br>        super.onListenerConnected()  <br>    }<br><br>    override fun onListenerDisconnected() {  <br>        super.onListenerDisconnected()<br>        <br>        if (componentName == null) {  <br>            componentName = ComponentName(this, this::class.java)  <br>        }  <br>        <br>        componentName?.let { requestRebind(it) }  <br>    }<br><br>    override fun onNotificationPosted(sbn: StatusBarNotification?) {<br>        val packageName = sbn?.packageName ?: &quot;&quot;<br>        val extras = sbn?.notification?.extras<br>        <br>        // Extract data from notification extras as needed<br>        val title = extras?.getCharSequence(&quot;android.title&quot;).toString()<br>        val text = extras?.getCharSequence(&quot;android.text&quot;).toString()<br>    }<br>}</pre><h4>Starting the Service and Requesting Permissions</h4><p>After configuring the service, you can start it by checking if the notification listener permission is granted. If not, prompt the user to enable it:</p><pre>fun redirectToSettings() {  <br>    Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS).apply {  <br>        activity.startActivityForResult(this, 1001)  <br>    }  <br>}<br><br>fun isNotificationListenerPermissionGranted(): Boolean {  <br>    val componentName = ComponentName(context, NotificationListener::class.java)  <br>    val enabledListeners = Settings.Secure.getString(context.contentResolver, &quot;enabled_notification_listeners&quot;)  <br>    return enabledListeners?.contains(componentName.flattenToString()) ?: false<br>}</pre><h4>Conclusion</h4><p>The NotificationListenerService in Android provides developers a powerful tool for creating apps that respond to real-time notifications, offering a way to add responsiveness and customization to the user experience. While the service presents specific considerations and permissions to address, following these steps can allow smooth integration into any app.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db54d65eca7" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/exploring-the-notification-listener-service-in-android-7db54d65eca7">Exploring the Notification Listener Service in Android</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Preference Datastore in Android]]></title>
            <link>https://medium.com/@raj2512flair/exploring-preference-datastore-in-android-ed1aaec1ed3a?source=rss-af4dc8a044ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed1aaec1ed3a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[jetpack-datastore]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[G. Raj Kumar]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 13:16:21 GMT</pubDate>
            <atom:updated>2024-11-09T09:00:09.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4yAI2W6x_VK4AZIL" /><figcaption>Photo by <a href="https://unsplash.com/@wacalke?utm_source=medium&amp;utm_medium=referral">Mateusz Wacławek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data storage is essential in Android development, especially when managing user-specific information such as settings, preferences, or onboarding statuses. Traditionally, Android developers relied on <strong>Room</strong> for structured databases and <strong>SharedPreferences</strong> for simpler, key-value storage needs. However, the <strong>Preference Datastore</strong> is a modern alternative that offers enhanced data consistency and performance. Unlike SharedPreferences, Preference Datastore is designed with Kotlin’s asynchronous programming in mind, leveraging coroutines and flows to enable secure, asynchronous data handling.</p><p>This guide dives into implementing Preference Datastore, setting it up for an efficient and safe data-handling experience. We’ll walk through configuring dependencies, establishing a robust architecture with dependency injection, and understanding how Datastore’s atomic transactions ensure data consistency and reliability.</p><h4>Understanding Preference Datastore</h4><p>Preference Datastore, one of the two types of Datastore available in Android, is ideal for simple, key-value data storage needs, much like SharedPreferences but optimized for Kotlin coroutines. It supports asynchronous programming and provides automatic transaction handling using <strong>ACID properties</strong> — ensuring that each read and write operation is atomic and consistent. This prevents race conditions and makes data handling smoother and more reliable.</p><h4>Implementation</h4><p>Step 1: Setting Up Gradle Dependencies</p><p>Add the required version of the Datastore Preferences library to libs.versions.toml:</p><pre>[versions]<br>datastorePreferences = &quot;1.1.1&quot;<br><br>[libraries]<br>androidx-datastore-preferences = { module = &quot;androidx.datastore:datastore-preferences&quot;, version.ref = &quot;datastorePreferences&quot; }</pre><p>Then import this dependency in your app module’s build.gradle.kts:</p><pre>//Datastore preferences  <br>implementation(libs.androidx.datastore.preferences)</pre><p>Step 2: Initializing Preference Datastore with Dependency Injection</p><p>For efficient access, initialize Preference Datastore in a DI module. In this example, we will store user-related information in Datastore. Here’s how to set it up in your persistence module:</p><pre>private const val USER_PREFERENCES = &quot;user_preferences&quot;  <br>  <br>@Module  <br>@InstallIn(SingletonComponent::class)  <br>object PersistenceModule {<br>    @Provides  <br>    @Singleton  <br>    fun providePreferencesDataStore(@ApplicationContext appContext: Context): DataStore&lt;Preferences&gt; {  <br>        return PreferenceDataStoreFactory.create(  <br>            corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() },<br>            scope = CoroutineScope(Dispatchers.IO + SupervisorJob()),  <br>            produceFile = { appContext.preferencesDataStoreFile(USER_PREFERENCES) }  <br>        )  <br>    }<br><br>    @Provides  <br>    @Singleton  <br>    fun providesUserPreferencesRepository(dataStore: DataStore&lt;Preferences&gt;) : UserPreferencesRepository {  <br>        return UserPreferencesRepositoryImpl(dataStore)  <br>    }<br>}</pre><p>Key Parameters Explained</p><ul><li><strong>corruptionHandler</strong>: Detects and manages data corruption. Here, ReplaceFileCorruptionHandler resets preferences to an empty state if corruption occurs.</li><li><strong>scope</strong>: Defines the coroutine scope for Datastore operations. Using Dispatchers.IO with SupervisorJob ensures that failed operations don’t disrupt others.</li><li><strong>produceFile</strong>: Specifies the file where Datastore reads and writes data.</li></ul><p>Step 3: Defining Preference Keys</p><p>Store preference keys in a separate file for easy access:</p><pre>object PreferencesKeys {  <br>    val IS_ONBOARDED = booleanPreferencesKey(&quot;user_onboarded&quot;)  <br>    val USER_ID = stringPreferencesKey(&quot;user_id&quot;)    <br>}</pre><p>Step 4: Building the UserPreferencesRepository</p><p>Define an interface for storing and retrieving user data:</p><pre>interface UserPreferencesRepository {  <br>    suspend fun getIsOnboardedData(): Boolean  <br>    suspend fun updateIsOnboardedData(isOnboarded: Boolean)  <br>    suspend fun getUserIdData(defaultValue: String? = null): String?  <br>    suspend fun updateUserIdData(userId: String)  <br>}</pre><p>Implement the interface, adding a helper function safeInvoke() for handling exceptions during data operations:class</p><pre>UserPreferencesRepositoryImpl @Inject constructor(private val dataStore: DataStore&lt;Preferences&gt;) : <br> UserPreferencesRepository { <br>   override suspend fun getIsOnboardedData(): Boolean { <br>     return safeInvoke { <br>       val preferences = dataStore.data.first() <br>       preferences[PreferencesKeys.IS_ONBOARDED] ?: false <br>     } <br>   }<br>  <br>   override suspend fun updateIsOnboardedData(isOnboarded: Boolean) { <br>     safeInvoke { <br>       dataStore.edit { preferences -&gt; <br>         preferences[PreferencesKeys.IS_ONBOARDED] = isOnboarded <br>       } <br>     }<br>   }<br>  <br>   override suspend fun getUserIdData(defaultValue: String?): String? { <br>     return safeInvoke { <br>       val preferences = dataStore.data.first() <br>       preferences[PreferencesKeys.USER_ID] ?: defaultValue <br>     }<br>   }<br>  <br>   override suspend fun updateUserIdData(userId: String) { <br>       safeInvoke { <br>           dataStore.edit { preferences -&gt; <br>               preferences[PreferencesKeys.USER_ID] = userId <br>           } <br>       }<br>   }<br>  <br>   private inline fun &lt;T&gt; safeInvoke(execute: () -&gt; T): T? { <br>       return try { <br>           execute() <br>       } catch (e: IOException) { <br>          Log.e(&quot;PreferencesRepository&quot;, &quot;IOException: ${e.localizedMessage}&quot;)<br>          null <br>       } catch (e: Exception) { <br>          Log.e(&quot;PreferencesRepository&quot;, &quot;Error: ${e.localizedMessage}&quot;)<br>          null <br>       }<br>   }<br>} </pre><p><strong>safeInvoke()</strong>: This helper function encapsulates potential errors when reading or writing data, ensuring your app can handle IO exceptions gracefully.</p><h4>Reading and Writing Data</h4><ul><li><strong>Reading Data</strong>: Use dataStore.data.first() to obtain a snapshot of data. For observing continuous updates, consider using dataStore.data.map { preferences -&gt; }.</li><li><strong>Writing Data</strong>: Update data transactionally using dataStore.edit { preferences -&gt; }. This atomic read-modify-write approach ensures that data is only updated when the entire operation is complete, maintaining consistency and avoiding race conditions.</li></ul><h3>Conclusion</h3><p>By switching from SharedPreferences to Preference Datastore, you’re enhancing your app’s data handling efficiency with a coroutine-friendly, transactionally safe approach. This migration aligns with modern Kotlin development practices, enabling a more responsive and reliable user experience. Thank you for reading, and happy coding with Datastore!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed1aaec1ed3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Establishing Connection with Bluetooth Classic in Android]]></title>
            <link>https://blog.stackademic.com/establishing-connection-with-bluetooth-classic-in-android-1f9f17c9a452?source=rss-af4dc8a044ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f9f17c9a452</guid>
            <category><![CDATA[bluetooth-speaker]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[bluetooth-connectivity]]></category>
            <category><![CDATA[bluetooth]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[G. Raj Kumar]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 20:16:48 GMT</pubDate>
            <atom:updated>2024-11-11T03:39:54.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mwOcy7RvEjhSAjJF" /><figcaption>Photo by <a href="https://unsplash.com/@yuliamatvienko?utm_source=medium&amp;utm_medium=referral">Yulia Matvienko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Interacting with mobile hardware is one of the most exciting aspects of Android development, particularly when it comes to Bluetooth technology. Bluetooth Classic, a widely used protocol for wireless communication, allows us to establish connections between devices, such as smartphones, speakers, and other peripherals. In this blog, we will focus on how to establish and disconnect a Bluetooth Classic connection in Android, discussing key components like UUIDs and the Advanced Audio Distribution Profile (A2DP), which is critical for streaming audio over Bluetooth.</p><p>While many existing tutorials cover scanning and listing available Bluetooth devices, this blog will emphasize how to build a reliable Bluetooth connection, leveraging A2DP for handling audio transmission. If you’re already familiar with scanning devices, you can refer to this excellent tutorial by Philipp Lackner on YouTube for additional background:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FA41hkHoYu4M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DA41hkHoYu4M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FA41hkHoYu4M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/08afac947b3b072c1579cba2984ca81d/href">https://medium.com/media/08afac947b3b072c1579cba2984ca81d/href</a></iframe><p>Now, let’s dive into the technical details of Bluetooth Classic and learn how to create a seamless connection for your Android applications!</p><h3>Interacting with Bluetooth Classic and its Complexities</h3><p>When working with Bluetooth in Android, developers typically encounter two types of devices: <strong>Bluetooth Classic</strong> and <strong>Bluetooth Low Energy (BLE)</strong>. In this post, we’ll focus on Bluetooth Classic, which is suitable for tasks that require sustained, high-bandwidth connections, like audio streaming. You may already know how to scan and list available devices, but our goal here is to manage device connections, particularly with A2DP, ensuring that devices like Bluetooth speakers can receive audio from your Android app.</p><p>Most developers try to establish a connection using a method like the one below:</p><pre>fun connectWithDevice(device: BluetoothDevice){<br>    try {<br>        val MY_UUID = UUID.fromString(&quot;00001101-0000-1000-8000-00805F9B34FB&quot;)<br>        val socket = device.createRfcommSocketToServiceRecord(MY_UUID)<br>        socket.connect()<br><br>        if (socket.isConnected) {<br>            val inputStream = socket.inputStream<br>            val outputStream = socket.outputStream<br>            Log.d(&quot;BluetoothController&quot;, &quot;connected&quot;)<br>        }<br>    } catch (e: SecurityException) {<br>        Log.d(&quot;BluetoothController&quot;, &quot;SecurityException error&quot;)<br>    } catch (e: IOException) {<br>        Log.d(&quot;BluetoothController&quot;, &quot;IOException error&quot;)<br>    } catch (e: Exception) {<br>        Log.d(&quot;BluetoothController&quot;, &quot;error&quot;)<br>    }<br>}</pre><p>In the above example, we use the <strong>UUID</strong> to identify the connection request. Specifically, the UUID we’re using here is for an <strong>SSP (Serial Port Profile)</strong> connection, which works great for communicating with Bluetooth serial boards. While this method may successfully log a connection event, it often falls short when trying to perform more specific tasks, such as playing audio on a Bluetooth speaker.</p><h4>Bluetooth Profiles: Why A2DP Matters</h4><p>Bluetooth communication is managed by profiles, which define how two devices communicate with each other. One of the most essential profiles for audio streaming is <strong>A2DP (Advanced Audio Distribution Profile)</strong>. A2DP allows high-quality audio to be transmitted from one device (such as your Android phone) to another (such as Bluetooth speakers or headphones).</p><p>To make audio streaming work, you must ensure that your connection is established using A2DP, not just SSP. This is where many developers encounter issues — connecting via SSP doesn’t enable audio transmission.</p><h4>BluetoothController.kt Interface</h4><p>We’ll start by creating an interface that outlines the functions required for managing Bluetooth devices. Our focus is on establishing and terminating connections, while additional functionality like scanning is kept out of scope for this particular example.</p><pre>interface BluetoothController {<br>    val scannedDevices: StateFlow&lt;List&lt;BluetoothDeviceApp&gt;&gt;<br>    val pairedDevice: StateFlow&lt;List&lt;BluetoothDeviceApp&gt;&gt;<br>    val bluetoothState: StateFlow&lt;BluetoothState&gt;<br><br>    fun resetBluetoothState()<br>    fun startDiscovery()<br>    fun stopDiscovery()<br>    suspend fun connectToDevice(device: BluetoothDeviceApp)<br>    suspend fun disconnectFromDevice(device: BluetoothDeviceApp)<br>}</pre><h4>Implementing Bluetooth Connection Logic</h4><p>Below is the implementation of the Bluetooth connection logic. Note that we’ve added proper permission checks and profile-specific connection handling, such as managing A2DP.</p><pre>@SuppressLint(&quot;MissingPermission&quot;)<br>class AndroidBluetoothController(<br>    private val context: Context<br>) : BluetoothController {<br>    private val bluetoothManager by lazy {<br>        context.getSystemService(BluetoothManager::class.java)<br>    }<br>    private val bluetoothAdapter by lazy {<br>        bluetoothManager.adapter<br>    }<br><br>    private var a2dp: BluetoothA2dp? = null<br><br>    override suspend fun connectToDevice(device: BluetoothDevice) {<br>        if (!hasPermissions(Manifest.permission.BLUETOOTH_CONNECT)) {<br>            return // Ensure permission is granted before proceeding<br>        }<br><br>        try {<br>            stopDiscovery() // Stop discovery before initiating a connection<br><br>            // Handle device bonding<br>            if (device.bondState == BluetoothDevice.BOND_NONE) {<br>            // if not already bonded, then need to create bond<br>                device.createBond().let { isBondAccepted -&gt;<br>                    if (isBondAccepted) {<br>                        connectA2dpProfile(device)<br>                    }<br>                }<br>            } else {<br>            // if device is already bonded<br>                connectA2dpProfile(device)<br>            }<br>        } catch (e: Exception) {<br>            Log.e(&quot;BluetoothController&quot;, &quot;Error during connection: ${e.message}&quot;)<br>        }<br>    }<br><br>    override suspend fun disconnectFromDevice(bluetoothDevice: BluetoothDevice) {<br>        try {<br>          // disconnect using A2dp profile, and remove the bond<br>          // Not all phones support this type of disconnection<br>          // In my case, redmi did while motorola didn&#39;t<br>            disconnectA2dpProfile {<br>                // Thus to support all device we use this method<br>                // calling hidden method via reflection to force disconnection<br>                bluetoothDevice::class.java.getMethod(&quot;removeBond&quot;).invoke(bluetoothDevice)<br><br>                a2dp = null // reset the variable<br>            }<br>        } catch (e: Exception) {<br>            Log.e(&quot;BluetoothController&quot;, &quot;Disconnection error: ${e.message}&quot;)<br>        }<br>    }<br><br>    private fun connectA2dpProfile(device: BluetoothDevice) {<br>        bluetoothAdapter.getProfileProxy(context, object : BluetoothProfile.ServiceListener {<br>            override fun onServiceConnected(profile: Int, proxy: BluetoothProfile?) {<br>                if (profile == BluetoothProfile.A2DP) {<br>                    a2dp = proxy as BluetoothA2dp<br>                    try {<br>                        a2dp!!.javaClass.getMethod(&quot;connect&quot;, BluetoothDevice::class.java).invoke(a2dp, device)<br>                        Log.d(&quot;BluetoothController&quot;, &quot;A2DP connected&quot;)<br>                    } catch (e: Exception) {<br>                        e.printStackTrace()<br>                    }<br>                }<br>            }<br><br>            override fun onServiceDisconnected(profile: Int) {<br>                if (profile == BluetoothProfile.A2DP) {<br>                    try {<br>                        a2dp?.javaClass?.getMethod(&quot;disconnect&quot;, BluetoothDevice::class.java)?.invoke(a2dp, device)<br>                        a2dp = null<br>                        Log.d(&quot;BluetoothController&quot;, &quot;A2DP disconnected&quot;)<br>                    } catch (e: Exception) {<br>                        e.printStackTrace()<br>                    }<br>                }<br>            }<br>        }, BluetoothProfile.A2DP)<br>    }<br><br>    private fun disconnectA2dpProfile(callback: () -&gt; Unit) {<br>        try {<br>            bluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, a2dp)<br>            callback()<br>        } catch (e: Exception) {<br>            e.printStackTrace()<br>        }<br>    }<br><br>    private fun hasPermissions(permission: String): Boolean {<br>        return if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) {<br>            context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED<br>        } else {<br>            true<br>        }<br>    }<br>}</pre><p>Additionally, To monitor connection and disconnection events, use a <strong>BroadcastReceiver</strong> that listens for specific Bluetooth actions. The receiver will update the UI or take appropriate actions depending on the state of the Bluetooth connection.</p><pre>private val btConnectionReceiver = BtConnectionReceiver { isConnected -&gt;<br>    if (isConnected) {<br>        // Logic when connected<br>    } else {<br>        // Logic when disconnected<br>    }<br>}<br><br>init {<br>    registerBtConnectionReceiver()<br>}<br><br>private fun registerBtConnectionReceiver() {<br>    if (!hasPermissions(Manifest.permission.BLUETOOTH_SCAN)) {<br>        return<br>    }<br><br>    val intentFilter = IntentFilter().apply {<br>        addAction(BluetoothDevice.ACTION_ACL_CONNECTED)<br>        addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)<br>        addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)<br>    }<br><br>    context.registerReceiver(btConnectionReceiver, intentFilter)<br>}</pre><p>This is your setup for Broadcast Receiver, where we send the result to the AndroidBluetoothController.kt via a callback method with boolean type:</p><pre>class BtConnectionReceiver(<br> private val connectionStatus: (Boolean) -&gt; Unit) : BroadcastReceiver()<br>{  <br>    @SuppressLint(&quot;MissingPermission&quot;)  <br>    override fun onReceive(context: Context?, intent: Intent?) {  <br>        when(action){  <br>            BluetoothDevice.ACTION_ACL_CONNECTED -&gt; {    <br>                connectionStatus(true)  <br>            }  <br>  <br>            BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED -&gt; {  <br>                Log.d(&quot;BtConnectionReceiver&quot;,&quot;Disconnecting...&quot;)  <br>            }  <br>            <br>            BluetoothDevice.ACTION_ACL_DISCONNECTED -&gt; {  <br>                connectionStatus(false) <br>            }  <br>        }  <br>    }  <br>}</pre><p>By using this broadcast receiver, your app will stay updated on connection status changes, helping you provide a smoother Bluetooth experience.</p><h3>Conclusion</h3><p>Establishing a Bluetooth Classic connection in Android, especially for handling audio streaming via A2DP, can be challenging due to the specific profiles involved. By following the outlined approach, you’ll be able to set up reliable connections and manage disconnections effectively. For additional resources, be sure to check out the linked YouTube tutorial and feel free to reach out if you need further assistance. Happy coding!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f9f17c9a452" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/establishing-connection-with-bluetooth-classic-in-android-1f9f17c9a452">Establishing Connection with Bluetooth Classic in Android</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type-Safe Nested Navigation in Jetpack Compose]]></title>
            <link>https://medium.com/@raj2512flair/type-safe-nested-navigation-in-jetpack-compose-aea900c9fdfa?source=rss-af4dc8a044ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/aea900c9fdfa</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[nested-navigation]]></category>
            <category><![CDATA[navigation-component]]></category>
            <category><![CDATA[navgraph]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[G. Raj Kumar]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 16:37:23 GMT</pubDate>
            <atom:updated>2024-08-04T06:07:58.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f6xdFbF_V21JiMSl" /><figcaption>Photo by <a href="https://unsplash.com/@mullyadii?utm_source=medium&amp;utm_medium=referral">Mulyadi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Navigating through different screens in an app efficiently and safely is crucial for providing a seamless user experience. The latest update in Navigation Compose introduces type safety, a feature that significantly simplifies the process of passing data between screens or destinations. This enhancement reduces errors and improves code readability and maintainability by leveraging Kotlin’s strong typing system. In this blog, we will explore how to implement type-safe nested navigation in Jetpack Compose. We’ll guide you through creating navigation graphs, defining routes with type safety, handling navigation events, and integrating these with your app’s architecture. Let’s dive in!</p><h4>First let’s import the dependencies we need for type safe navigation</h4><p>Configure your app level gradle file</p><pre>plugins {<br>    alias(libs.plugins.androidApplication)<br>    alias(libs.plugins.jetbrainsKotlinAndroid)<br>    alias(libs.plugins.compose.compiler)<br>    alias(libs.plugins.jetbrains.kotlin.serialization)<br>    id(&quot;kotlin-parcelize&quot;) // needed only for non-primitive classes<br>}<br><br>dependencies {<br>    //navigation<br>    implementation(libs.androidx.navigation.compose)<br>    implementation(libs.kotlinx.serialization.json)<br>}</pre><p>Configure your lib.versions.toml file</p><pre>[versions]<br>kotlinxSerializationJson = &quot;1.6.3&quot;<br>kotlinxSerialization = &quot;1.9.23&quot;<br>navigationCompose = &quot;2.8.0-beta05&quot;<br><br>[libraries]<br>#navigation<br>androidx-navigation-compose = { group = &quot;androidx.navigation&quot;, name = &quot;navigation-compose&quot;, version.ref = &quot;navigationCompose&quot; }<br>kotlinx-serialization-json = { module = &quot;org.jetbrains.kotlinx:kotlinx-serialization-json&quot;, version.ref = &quot;kotlinxSerializationJson&quot; }<br><br>[plugins]<br>jetbrains-kotlin-serialization = { id =&quot;org.jetbrains.kotlin.plugin.serialization&quot;, version.ref = &quot;kotlinxSerialization&quot;}</pre><p>Configure your project level gradle file</p><pre>plugins {<br>    alias(libs.plugins.androidApplication) apply false<br>    alias(libs.plugins.jetbrainsKotlinAndroid) apply false<br>    alias(libs.plugins.compose.compiler) apply false<br>    alias(libs.plugins.androidLibrary) apply false<br>    alias(libs.plugins.jetbrains.kotlin.serialization) apply false<br>}</pre><h4>Setting Up Navigation Graphs</h4><p>Let’s start by creating our navigation graphs. In this example, we will create a root navigation graph and integrate multiple nested graphs into it. Here’s how to set up the root navigation graph:</p><pre>@Composable  <br>fun CentralNavigation(navController: NavHostController) {  <br>    NavHost(navController = navController, startDestination = HomeScreens) {  <br>        homeNavGraph(navController)  <br>        jobsNavGraph(navController)  <br>        serviceNavGraph(navController)  <br>        schemeNavGraph(navController)    <br>    }  <br>}</pre><p>In this setup, we pass the navController to each nested graph, allowing it to handle navigation independently.</p><h4>Defining Type-Safe Routes</h4><p>To define routes with type safety, we can use objects and data classes instead of strings. This approach eliminates typos and enhances code readability. Here’s an example:</p><pre>@Serializable  <br>object JobsScreens  <br>  <br>@Serializable  <br>object JobRoot  <br>  <br>@Serializable  <br>data class JobCategory(val categoryName: String)  <br>  <br>@Serializable  <br>object JobEligibility</pre><p>With these definitions, we can now set up our nested navigation graph.</p><h4>Creating Nested Navigation Graphs</h4><p>We will create a navigation graph for job-related screens. This example demonstrates how to use type-safe routes:</p><pre>fun NavGraphBuilder.jobsNavGraph(navController: NavController) {  <br>    navigation&lt;JobsScreens&gt;(startDestination = JobRoot) {  <br>        composable&lt;JobRoot&gt; {  <br>            JobRootScreen {  <br>                handleJobNavigation(it, navController)  <br>            }  <br>        }        <br>        composable&lt;JobCategory&gt; {  <br>            val args = it.toRoute&lt;JobCategory&gt;()  <br>            CategoryDetailScreen(categoryName = args.categoryName) {  <br>                handleJobNavigation(it, navController)  <br>            }  <br>        }        <br>        composable&lt;JobEligibility&gt; {  <br>            JobEligibilityForm()  <br>        }  <br>    }<br>}</pre><h4>Handling Navigation Events</h4><p>To handle navigation events, we create a helper function that processes different navigation actions. Here’s an example:</p><pre>fun handleJobNavigation(event: JobNavigationEvent, navController: NavController) {  <br>    when(event) {  <br>        is JobNavigationEvent.OnCategoryClick -&gt; navController.navigate(JobCategory(categoryName = event.categoryName))<br>          <br>        JobNavigationEvent.OnBackPressed -&gt; navController.popBackStack()<br>          <br>        JobNavigationEvent.OnApplyNowClick -&gt; navController.navigate(JobEligibility)  <br>    }<br>}</pre><h4>Implementing Navigation Helper Functions</h4><p>Creating a sealed class to list all navigation events ensures a clear and type-safe way to manage navigation:</p><pre>sealed class JobNavigationEvent {  <br>    data object OnBackPressed : JobNavigationEvent()  <br>    data class OnCategoryClick(val categoryName: String) : JobNavigationEvent()  <br>    data object OnApplyNowClick : JobNavigationEvent()  <br>}</pre><h4>Integrating with Composables</h4><p>We can handle navigation events within composables by exposing lambda functions. Here’s an example of a composable screen:</p><pre>@Composable  <br>fun JobRootScreen(handleNavigation: (JobNavigationEvent) -&gt; Unit) {<br>    Scaffold(topBar = { SecondaryHeader() }) {  <br>        Column(  <br>            modifier = Modifier  <br>                .padding(it)  <br>                .fillMaxSize()  <br>        ) {<br>            Button(onClick = { handleNavigation(JobNavigationEvent.OnCategoryClick(&quot;Marketing Job&quot;))})<br>        }<br>    }<br>}</pre><h4>Fetching and Using Passed Data</h4><p>On the CategoryDetailScreen, we can fetch the passed data and perform operations like making API calls:</p><pre>@Composable  <br>fun CategoryDetailScreen(<br>    categoryName: String,<br>    viewModel: CategoryDetailViewModel = hiltViewModel(),<br>    handleNavigation: (JobNavigationEvent) -&gt; Unit<br>) {  <br>    val state by viewModel.state.collectAsState()<br> <br>    LaunchedEffect(Unit) {<br>        viewModel.getCategoryDetails(categoryName)<br>    }<br>}</pre><h4>Integrating Nested Navigation with Bottom Navigation</h4><blockquote>To integrate nested navigation with a bottom navigation bar, refer to the detailed blog <a href="https://medium.com/@raj2512flair/type-safe-bottom-navigation-in-jetpack-compose-3daee4a8e306"><em>here</em></a><em>.</em></blockquote><h3>Conclusion</h3><p>Thank you for taking the time to read through this tutorial. Implementing type-safe nested navigation in Jetpack Compose not only enhances your app’s reliability but also improves the overall development experience. If you have any questions or suggestions, feel free to reach out. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aea900c9fdfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type-Safe Bottom Navigation in Jetpack Compose]]></title>
            <link>https://medium.com/@raj2512flair/type-safe-bottom-navigation-in-jetpack-compose-3daee4a8e306?source=rss-af4dc8a044ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/3daee4a8e306</guid>
            <category><![CDATA[bottomnavigationbar]]></category>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[jetpack-navigation]]></category>
            <dc:creator><![CDATA[G. Raj Kumar]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 11:02:49 GMT</pubDate>
            <atom:updated>2024-08-04T06:04:21.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JNRbn67z1w-uEnpA" /><figcaption>Photo by <a href="https://unsplash.com/@roadtripwithraj?utm_source=medium&amp;utm_medium=referral">Road Trip with Raj</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With the latest update in Navigation Compose, Jetpack Compose developers have been blessed with a highly anticipated feature: type safety. This enhancement significantly simplifies data passing between screens or destinations, making the development process smoother and less error-prone. Type safety ensures that navigation arguments are strongly typed, reducing runtime errors and enhancing code readability and maintainability. In this blog, we will dive into the implementation of type-safe bottom navigation in Jetpack Compose. We’ll explore setting up navigation destinations, creating a bottom navigation bar, and managing navigation events efficiently. For comprehensive details, refer to the official Android documentation. Let’s get started!</p><h4><strong>First let’s import the dependencies we need for type safe navigation</strong></h4><p>Configure your app level gradle file</p><pre>plugins {<br>    alias(libs.plugins.androidApplication)<br>    alias(libs.plugins.jetbrainsKotlinAndroid)<br>    alias(libs.plugins.compose.compiler)<br>    alias(libs.plugins.jetbrains.kotlin.serialization)<br>    id(&quot;kotlin-parcelize&quot;) // needed only for non-primitive classes<br>}<br>dependencies {<br>    //navigation<br>    implementation(libs.androidx.navigation.compose)<br>    implementation(libs.kotlinx.serialization.json)<br>}</pre><p>Configure your lib.versions.toml file</p><pre>[versions]<br>kotlinxSerializationJson = &quot;1.6.3&quot;<br>kotlinxSerialization = &quot;1.9.23&quot;<br>navigationCompose = &quot;2.8.0-beta05&quot;<br><br>[libraries]<br>#navigation<br>androidx-navigation-compose = { group = &quot;androidx.navigation&quot;, name = &quot;navigation-compose&quot;, version.ref = &quot;navigationCompose&quot; }<br>kotlinx-serialization-json = { module = &quot;org.jetbrains.kotlinx:kotlinx-serialization-json&quot;, version.ref = &quot;kotlinxSerializationJson&quot; }<br><br>[plugins]<br>jetbrains-kotlin-serialization = { id =&quot;org.jetbrains.kotlin.plugin.serialization&quot;, version.ref = &quot;kotlinxSerialization&quot;}</pre><p>Configure your project level gradle file</p><pre>plugins {<br>    alias(libs.plugins.androidApplication) apply false<br>    alias(libs.plugins.jetbrainsKotlinAndroid) apply false<br>    alias(libs.plugins.compose.compiler) apply false<br>    alias(libs.plugins.androidLibrary) apply false<br>    alias(libs.plugins.jetbrains.kotlin.serialization) apply false<br>}</pre><h4>Setting Up Navigation Destinations</h4><p>To start, we need to define our navigation destinations. Each destination represents a screen in our application. We’ll use the @Serializable annotation to mark our destination objects. Here’s how we set it up:</p><pre>@Serializable<br>object HomeScreens<br><br>@Serializable<br>object JobsScreens<br><br>@Serializable<br>object SchemesScreens<br><br>@Serializable<br>object ServicesScreens</pre><h4>Sealed Classes for Navigation</h4><p>Next, we use sealed classes to define our bottom navigation screens. Sealed classes allow us to create a restricted class hierarchy, ensuring that all subclasses are known at compile-time. This is how we set up our destinations with respective icons and names:</p><pre>@Serializable<br>sealed class BottomScreens&lt;T&gt;(val name: String, val icon: Int, val route: T) {<br>    @Serializable<br>    data object Home : BottomScreens&lt;HomeScreens&gt;(name = &quot;Home&quot;, icon = R.drawable.outline_home, route = HomeScreens)<br>    <br>    @Serializable<br>    data object Job : BottomScreens&lt;JobsScreens&gt;(name = &quot;Job&quot;, icon = R.drawable.outline_email, route = JobsScreens)<br>    <br>    @Serializable<br>    data object Scheme : BottomScreens&lt;SchemesScreens&gt;(name = &quot;Scheme&quot;, icon = R.drawable.outline_list, route = SchemesScreens)<br>    <br>    @Serializable<br>    data object Service : BottomScreens&lt;ServicesScreens&gt;(name = &quot;Service&quot;, icon = R.drawable.outline_build, route = ServicesScreens)<br>}</pre><p>In this setup, name is the label displayed in the bottom navigation bar, and icon is the corresponding icon for each destination.</p><h4>Creating the Bottom Navigation Bar</h4><p>The main part of our implementation involves creating the bottom navigation bar and handling navigation events. Here’s how to set it up in Jetpack Compose:</p><pre>@Composable<br>fun AppBottomNavigation(navController: NavController) {<br>    val bottomScreens = remember {<br>        listOf(<br>            BottomScreens.Home,<br>            BottomScreens.Scheme,<br>            BottomScreens.Service,<br>            BottomScreens.Job<br>        )<br>    }<br><br>    BottomNavigation(backgroundColor = MaterialTheme.colorScheme.background) {<br>        val navBackStackEntry by navController.currentBackStackEntryAsState()<br>        val currentDestination = navBackStackEntry?.destination<br><br>        bottomScreens.forEach { screen -&gt;<br>            val isSelected = currentDestination?.hierarchy?.any { it.route == screen.route::class.qualifiedName } == true<br>            BottomNavigationItem(<br>                selected = isSelected,<br>                onClick = {<br>                    navController.navigate(screen.route) {<br>                        popUpTo(navController.graph.findStartDestination().id) {<br>                            saveState = true<br>                        }<br>                        launchSingleTop = true <br>                        restoreState = true<br>                    }<br>                },<br>                icon = {<br>                    Icon(<br>                        imageVector = ImageVector.vectorResource(screen.icon),<br>                        contentDescription = screen.name<br>                    )<br>                },<br>                label = {<br>                    Text(<br>                        text = screen.name,<br>                        style = MaterialTheme.typography.bodyMedium,<br>                        fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,<br>                        color = if (isSelected) MaterialTheme.colorScheme.primary else Color.Gray<br>                    )<br>                },<br>                selectedContentColor = MaterialTheme.colorScheme.primary,<br>                unselectedContentColor = MaterialTheme.colorScheme.onBackground<br>            )<br>        }<br>    }<br>}</pre><p>This code snippet ensures that the bottom navigation bar is set up with the defined screens, and handles navigation events appropriately. The popUpTo method prevents building a stack of destinations in the back stack for bottom navigation. The saveState parameter saves the state of the destination before popping, while launchSingleTop avoids duplication of destinations in the navigation back stack. Lastly, restoreState helps continue with the saved state.</p><h4>Integrating Bottom Navigation in the Main Activity</h4><p>Finally, we integrate our bottom navigation bar into the MainActivity. Here’s how to do it:</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContent {<br>            NaxtreDemoTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = Color.White<br>                ) {<br>                    val navController = rememberNavController()<br>                    CentralNavigation(navController = navController)<br>                    Box(<br>                        modifier = Modifier<br>                            .fillMaxSize()<br>                            .systemBarsPadding(),<br>                        contentAlignment = Alignment.BottomCenter<br>                    ) {<br>                        AppBottomNavigation(navController = navController)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>This setup ensures that our bottom navigation bar is available globally in the app, providing a seamless navigation experience.</p><h3>Conclusion</h3><p>Thank you for taking the time to read through this tutorial. Implementing type-safe bottom navigation in Jetpack Compose not only enhances your app’s reliability but also improves the overall development experience. If you have any questions or suggestions, feel free to reach out. Happy coding!</p><h3>FAQs</h3><ol><li>What is type safety in navigation?</li></ol><p>Type safety ensures that navigation arguments are strongly typed, reducing runtime errors and enhancing code readability.</p><p>2. How do I prevent destination duplication in the back stack?</p><p>Use launchSingleTop = true in the navController.navigate() method to avoid duplication.</p><p>3. What is the purpose of saveState in navigation?</p><p>saveState preserves the state of the destination before it is popped from the back stack.</p><p>4. Can I customize the bottom navigation bar appearance?</p><p>Yes, you can customize the bottom navigation bar’s appearance by modifying its color scheme, typography, and iconography.</p><p>5. How do I test bottom navigation in Jetpack Compose?</p><p>You can test bottom navigation by writing unit tests for your navigation components and using Jetpack Compose testing libraries to verify navigation behavior.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3daee4a8e306" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating from kapt to KSP: Improving Build Performance with KSP for Dagger and RoomDB]]></title>
            <link>https://medium.com/@raj2512flair/migrating-from-kapt-to-ksp-improving-build-performance-with-ksp-for-dagger-and-roomdb-2e66d6971013?source=rss-af4dc8a044ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e66d6971013</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[kapt]]></category>
            <category><![CDATA[ksp]]></category>
            <dc:creator><![CDATA[G. Raj Kumar]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 10:53:18 GMT</pubDate>
            <atom:updated>2024-04-07T10:53:18.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4Zf2t4eajJfk_SL_tX5Lw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kirsten_frank?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Kirsten Frank</a> on <a href="https://unsplash.com/photos/a-man-riding-a-wave-on-top-of-a-surfboard-o1sXiz_LU1A?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In the realm of Android development and Kotlin, build performance is often a critical concern. Migrating from the traditional kapt (Kotlin Annotation Processing Tool) to KSP (Kotlin Symbol Processing) offers significant advantages in terms of build speed and developer experience. In this post, we’ll explore the process of transitioning from kapt to KSP and how it can enhance your Kotlin development workflow.</p><h3>Advantages of KSP over kapt</h3><p>The shift from kapt to KSP brings forth several compelling benefits:</p><p>1. <strong>Improved Build Performance</strong>: KSP operates independently of the JVM, resulting in faster build times compared to kapt.<br> <br>2. <strong>Kotlin-Only Symbols</strong>: KSP allows processors to understand Kotlin-only symbols, which enables a more idiomatic Kotlin API design.</p><p>3. <strong>Enhanced Processor Integration</strong>: Unlike kapt, processors in KSP interact with Kotlin symbols directly, rather than viewing input programs from Java’s perspective.</p><p>Now, let’s dive into the implementation steps to migrate from kapt to KSP.</p><h3>Getting Started with KSP</h3><p>To begin utilizing KSP in your project, ensure you’re using Kotlin version `1.9.10` or later. Update your project module’s `build.gradle.kts` to include:</p><pre>// in project module<br>plugins {<br> id(&quot;org.jetbrains.kotlin.android&quot;) version &quot;1.9.10&quot; apply false<br>}<br><br>// in app module<br>kotlin {<br> kotlinCompilerExtensionVersion = &quot;1.5.3&quot; // Ensure compatibility with KSP<br>}</pre><p>Next, add the KSP dependency to your project level module:</p><pre>plugins {<br> id(&quot;com.android.application&quot;) version &quot;8.2.2&quot; apply false<br> id(&quot;org.jetbrains.kotlin.android&quot;) version &quot;1.9.10&quot; apply false<br> id(&quot;com.google.devtools.ksp&quot;) version &quot;1.9.10–1.0.13&quot; apply false // ksp<br>}</pre><p>In your app level module, integrate the KSP plugin:</p><pre>plugins {<br> id(&quot;com.android.application&quot;)<br> id(&quot;org.jetbrains.kotlin.android&quot;)<br> id(&quot;com.google.devtools.ksp&quot;) // ksp<br>}</pre><h3>Integrating KSP with Dagger Hilt</h3><p>If you’re using Dagger Hilt, replace the existing kapt dependency with KSP:</p><pre>// Remove kapt dependency<br>// kapt(&quot;com.google.dagger:hilt-compiler:2.46.1&quot;)<br><br>// Add KSP dependency<br>ksp(&quot;com.google.dagger:hilt-compiler:2.46.1&quot;)</pre><p>Optionally, you can remove the `kapt` block from your configuration:</p><pre>// Remove kapt block<br>// kapt {<br>// correctErrorTypes true<br>// }</pre><h3>Leveraging KSP for Room</h3><p>For Room database integration, update your dependencies to use KSP:</p><pre>val room_version = &quot;2.6.1&quot;<br>// Room dependencies with KSP<br>implementation(&quot;androidx.room:room-runtime:$room_version&quot;)<br>ksp(&quot;androidx.room:room-compiler:$room_version&quot;)<br>implementation(&quot;androidx.room:room-ktx:$room_version&quot;)</pre><h3>Conclusion</h3><p>By migrating from kapt to KSP, you’re embracing a more efficient and Kotlin-centric approach to annotation processing. This transition not only enhances build performance but also aligns with modern Kotlin development practices.</p><p>Thanks for reading! Happy coding with Kotlin Symbol Processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e66d6971013" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying API Responses with Sealed Classes and Coroutines: Retrofit]]></title>
            <link>https://blog.stackademic.com/simplifying-api-responses-with-sealed-classes-and-coroutines-0571bc211d11?source=rss-af4dc8a044ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/0571bc211d11</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[retrofit2]]></category>
            <category><![CDATA[api-response]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <dc:creator><![CDATA[G. Raj Kumar]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 07:20:53 GMT</pubDate>
            <atom:updated>2024-07-28T09:02:54.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YruEK6hicc_4NzgglfMxg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@wolfgang_hasselmann?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Wolfgang Hasselmann</a> on <a href="https://unsplash.com/photos/the-sun-is-setting-over-the-ocean-on-a-cloudy-day-d6DSBUVt96Q?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In the realm of modern app development, managing API responses efficiently is paramount. It entails not only sending network requests but also handling various states like success, error, or exception gracefully. In this tutorial, we’ll explore how to leverage Kotlin’s sealed classes along with coroutines to streamline this process, making our code more robust and comprehensible.</p><h3>Setting up Dependency Injection with Dagger Hilt and Retrofit</h3><p>To begin, let’s establish our codebase for making API calls using Dagger Hilt for dependency injection. We’ll utilize Retrofit to define an interface for making these calls.</p><pre>// RetrofitModule.kt<br>@Module<br>@InstallIn(SingletonComponent::class)<br>object RetrofitModule {<br><br> // Provides base URL for Retrofit<br> @Provides<br> fun provideBaseUrl(): String = &quot;https://ott-details.p.rapidapi.com&quot;<br><br><br>// Provides Retrofit instance<br> @Provides<br> @Singleton<br> fun provideRetrofit(baseUrl: String): Retrofit =<br> Retrofit.Builder()<br> .baseUrl(baseUrl)<br> .addConverterFactory(GsonConverterFactory.create())<br> .build()<br><br><br>// Provides ApiService instance<br> @Provides<br> @Singleton<br> fun provideApiService(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java)<br><br><br>// Provides RemoteDataSource instance<br> @Provides<br> @Singleton<br> fun provideRemoteDataSource(apiService: ApiService) : MovieRemoteDataSource {<br> return MovieRemoteDataSource(apiService)<br> }<br><br>}</pre><pre>// ApiService.kt<br>interface ApiService {<br> @GET(&quot;/advancedsearch&quot;)<br> suspend fun searchAllMovies(<br> @Query(&quot;start_year&quot;) startYear: Int,<br> @Query(&quot;end_year&quot;) endYear: Int,<br> @Query(&quot;language&quot;) language: String,<br> @Query(&quot;genre&quot;) genre: String = &quot;&quot;,<br> @Query(&quot;type&quot;) type: String,<br> @Query(&quot;sort&quot;) sort: String,<br> @Query(&quot;page&quot;) page: Int<br> ): Response&lt;HomeResult&gt;<br>}</pre><p>Next we will write the interface to make API calls using retrofit, here i am fetching movies data from a remote API service, as shown above.</p><h3>Simplifying Response Handling with Sealed Classes</h3><p>Now, let’s delve into designing a sealed class to encapsulate our Retrofit responses. This will offer a structured approach to manage the various states of API responses.</p><pre>sealed class NetworkResult&lt;T:Any&gt; {<br> data class Success&lt;T: Any&gt;(val data: T): NetworkResult&lt;T&gt;()<br> data class Error&lt;T: Any&gt;(val code: Int, val message:String?): NetworkResult&lt;T&gt;()<br> data class Exception&lt;T:Any&gt;(val e: Throwable) : NetworkResult&lt;T&gt;()<br>}</pre><h3>Creating a DSL for Wrapping Responses</h3><p>To further simplify the process of wrapping API responses, we’ll create a DSL (Domain Specific Language) function. This function will take a suspend function returning a Retrofit Response and encapsulate it within our sealed class.</p><pre>suspend fun &lt;T : Any&gt; handleApi(execute: suspend () -&gt; Response&lt;T&gt;) : NetworkResult&lt;T&gt;{<br> return try {<br> val response = execute()<br> val body = response.body()<br><br> if(response.isSuccessful &amp;&amp; body != null){<br>   NetworkResult.Success(data = body)<br> } else {<br>   NetworkResult.Error(code = response.code(), message = response.message())<br> }<br> } catch (e: HttpException){<br>   NetworkResult.Error(code = e.code(), message = e.message())<br> } catch(e: UnknownHostException){<br>   NetworkResult.Error(code = 404, message = &quot;No known host&quot;)<br> }catch (e: Throwable){<br>   NetworkResult.Exception(e)<br> }<br>}</pre><h3>Wrapping API Responses in Sealed Classes</h3><p>Moving on, let’s utilize our DSL function `handleApi` to wrap the API responses within our sealed classes. This will be implemented within the class responsible for making API calls.</p><pre>class MovieRemoteDataSource @Inject constructor(private val apiService: ApiService) {<br> suspend fun searchAllMovies(): NetworkResult&lt;HomeResult&gt; {<br> return handleApi {<br>     apiService.searchAllMovies(<br>     startYear = 1970,<br>     endYear = 2020,<br>     language = &quot;english&quot;,<br>     genre = &quot;action&quot;,<br>     type = &quot;movie&quot;,<br>     sort = &quot;latest&quot;,<br>     page = 1<br>     )<br>   }<br> }<br>}</pre><h3>Handling Responses in ViewModel</h3><p>Finally, let’s handle these wrapped responses in our ViewModel using coroutines. We’ll emit different states based on the response received, providing a seamless user experience.</p><pre>@HiltViewModel<br>class HomeViewModel @Inject constructor(private val movieRemoteDataSource: MovieRemoteDataSource) :<br> ViewModel() {<br><br> // Mutable state to hold movie response<br> var allMoviesResponse: List&lt;Result&gt; by mutableStateOf(listOf())<br><br>// Mutable state flow for different movie states<br> private val _movieState = MutableStateFlow&lt;MovieState&gt;(MovieState.START)<br> val movieState = _movieState.asStateFlow()<br><br>// Coroutine function to get random movies<br> fun getRandomMovies() {<br> viewModelScope.launch {<br> when (val response = movieRemoteDataSource.searchAllMovies()) {<br> is NetworkResult.Success -&gt; {<br> allMoviesResponse = response.data.results ?: emptyList()<br> _movieState.emit(MovieState.SUCCESS(allMoviesResponse))<br> }<br> is NetworkResult.Error -&gt; {<br> _movieState.emit(MovieState.FAILURE(&quot;${response.code} with ${response.message}&quot;))<br> }<br> is NetworkResult.Exception -&gt; {<br> _movieState.emit(MovieState.FAILURE(&quot;${response.e.message} and ${response.e}&quot;))<br> }<br> }<br> }<br> }<br>}<br><br>// Sealed class to represent different movie states<br>sealed class MovieState {<br> object START : MovieState()<br> data class SUCCESS&lt;T&gt;(val data: T): MovieState()<br> data class FAILURE(val message: String) : MovieState()<br>}</pre><p>By leveraging sealed classes, coroutines, and a DSL for wrapping responses, we’ve simplified the process of handling API responses in our Android application. This approach not only makes our code cleaner but also enhances its readability and maintainability.</p><p>Thank you for taking the time to read through this tutorial. I hope you found it insightful and beneficial for your app development endeavors. If you have any questions or suggestions, feel free to reach out. Happy coding!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0571bc211d11" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/simplifying-api-responses-with-sealed-classes-and-coroutines-0571bc211d11">Simplifying API Responses with Sealed Classes and Coroutines: Retrofit</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>