<?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 Chirag Vasani on Medium]]></title>
        <description><![CDATA[Stories by Chirag Vasani on Medium]]></description>
        <link>https://medium.com/@cpvasani48?source=rss-326679117500------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GP8rzq_I6LgtSqh4yuU1fA.jpeg</url>
            <title>Stories by Chirag Vasani on Medium</title>
            <link>https://medium.com/@cpvasani48?source=rss-326679117500------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:35:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cpvasani48/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[ Android 15 Behavior Changes: What Developers Need to Know (And Why You Should Care!)]]></title>
            <link>https://medium.com/@cpvasani48/android-15-behavior-changes-what-developers-need-to-know-and-why-you-should-care-781151bee548?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/781151bee548</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[updates]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Tue, 20 May 2025 18:21:28 GMT</pubDate>
            <atom:updated>2025-05-20T18:21:28.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*hAVwybEpZbBPDbKBUuAhUA.png" /></figure><p>Android 15 is here, and it’s packed with <strong>game-changing updates</strong> that will impact how your apps behave. Whether you’re dealing with <strong>foreground services, security, or UI tweaks</strong>, this guide breaks down the key changes — <strong>with a fun twist!</strong></p><h4>✍️ For Short Remember Memory(TL;DR — Quick Takeaways)</h4><pre>✅ Foreground Services: Now have a 6-hour limit (⏳ Time&#39;s up!)<br>✅ Security: Stricter rules on background launches (🚫 No more sneaky stuff!)<br>✅ UI: Edge-to-edge by default (📱 Goodbye, ugly black bars!)<br>✅ Text: Smarter rendering for complex scripts (✍️ Looking fancy!)</pre><h3>🔥 Hot Changes in Android 15 (API 35+)</h3><h4>1. ⏳ Foreground Services Now Have a “Time’s Up!” Moment</h4><p>📌 <strong>What’s New?</strong></p><ul><li>dataSync and the new mediaProcessing services now <strong>auto-timeout after 6 hours</strong> (within 24 hours).</li><li>The system calls Service.onTimeout()—if you ignore it, <strong>BOOM!</strong> RemoteServiceException.</li></ul><p>🎯 <strong>Why Should You Care?</strong></p><blockquote>“Time is what we want most, but what we use worst.”<em> — William Penn<br>⏳ </em><strong><em>Your app can’t run forever in the background anymore!</em></strong></blockquote><p>🛠 <strong>Fix It Like a Pro:</strong><br>✅ Implement onTimeout() and call stopSelf()<br>✅ Keep service runtime under 6 hours<br>✅ Use WorkManager for long tasks</p><h3>2. 🔒 Security: No More Sneaky Background Shenanigans</h3><h4>📌 <strong>What’s New?</strong></h4><ul><li>BOOT_COMPLETED<strong> receivers</strong> can no longer launch certain foreground services (e.g., camera, microphone).</li><li>SYSTEM_ALERT_WINDOW<strong> apps</strong> need a <strong>visible overlay</strong> to start foreground services.</li></ul><p>🎯 <strong>Why Should You Care?</strong></p><blockquote>“Security is not a product, but a process.”<em> — Bruce Schneier<br>🚫 </em><strong><em>Malicious apps can’t hijack your phone at boot!</em></strong></blockquote><p>🛠 <strong>Fix It Like a Pro:</strong><br>✅ Check if your overlay is visible before launching services<br>✅ Test with:</p><pre>adb shell am compat enable FGS_BOOT_COMPLETED_RESTRICTIONS your.package.name</pre><h3>3. 🌐 Edge-to-Edge UI: Bye-Bye, Ugly Black Bars!</h3><h4>📌 <strong>What’s New?</strong></h4><ul><li><strong>Apps are edge-to-edge by default</strong> (content draws behind system bars).</li><li><strong>No more </strong>setStatusBarColor()<strong>—deprecated!</strong></li></ul><p>🎯 <strong>Why Should You Care?</strong></p><blockquote>“Design is not just what it looks like. Design is how it works.”<em> — Steve Jobs</em></blockquote><h4><em>📱 </em><strong><em>Your app must now handle insets properly — or risk UI chaos!</em></strong></h4><p>🛠 <strong>Fix It Like a Pro:</strong><br>✅ Use WindowInsets to avoid hidden UI<br>✅ For <strong>Compose</strong>: Modifier.systemBarsPadding()<br>✅ For <strong>Views</strong>: ViewCompat.setOnApplyWindowInsetsListener()</p><p><em>(Image: Android’s new edge-to-edge enforcement in action!)</em></p><h3>4. ✍️ Text Rendering Just Got Smarter</h3><p>📌 <strong>What’s New?</strong></p><ul><li>elegantTextHeight=true<strong> by default</strong> (better readability for Arabic, Thai, etc.).</li><li><strong>Complex scripts (e.g., cursive fonts) now avoid clipping!</strong></li></ul><p>🎯 <strong>Why Should You Care?</strong></p><blockquote>“Typography is the voice of the written word.”<em><br>📜 </em><strong><em>Your text will look way better — but test for layout shifts!</em></strong></blockquote><p>🛠 <strong>Fix It Like a Pro:</strong><br>✅ Test languages like <strong>Arabic, Thai, Burmese</strong><br>✅ Use:</p><pre>&lt;TextView<br>    android:useBoundsForWidth=&quot;true&quot;<br>    android:shiftDrawingOffsetForStartOverhang=&quot;true&quot; /&gt;</pre><h3>🎯 Key Takeaways</h3><p>✔ <strong>Foreground Services:</strong> 6-hour limit, handle onTimeout()<br>✔ <strong>Security:</strong> No more background tricks—check your PendingIntents!<br>✔ <strong>UI:</strong> Edge-to-edge is <strong>mandatory</strong>—insets are your friend<br>✔ <strong>Text:</strong> Locale-aware heights, better script handling</p><h3>🚀 What’s Next?</h3><p>📌 <strong>Test your app on Android 15 Beta now!</strong><br>📌 <strong>Use </strong>StrictMode<strong> to catch unsafe intents</strong><br>📌 <strong>Check for deprecated APIs</strong></p><blockquote>“The only way to do great work is to love what you do.”<em> — Steve Job</em></blockquote><p><strong>Happy coding!</strong> 👨‍💻👩‍💻</p><p><em>(Need a quick checklist? Read </em><a href="https://developer.android.com/about/versions/15/behavior-changes-15"><em>Android 15 migration guide here!)</em> </a>🚀</p><h3>👏 Closing Thoughts</h3><blockquote>“The best way to predict the future is to create it.”<em> — Abraham Lincoln</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Dm_qGzNvCIAikv8" /><figcaption>Photo by <a href="https://unsplash.com/@libraryofcongress?utm_source=medium&amp;utm_medium=referral">Library of Congress</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Happy coding, and may your apps thrive on Android 15!</strong> 🚀</p><p><strong>👋 Until next time,</strong><br><strong>[Chirag Vasani]</strong></p><p>🔗<a href="https://www.linkedin.com/in/chiragkumar-vasani-a5a4a024a/"><strong>LinkedIn </strong></a><strong>| </strong><a href="https://github.com/ChiragVasaniP"><strong>GitHub</strong></a></p><p><strong>👏👏👏</strong> <em>Virtual applause for making it this far!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=781151bee548" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android NDK Security: Protecting Sensitive Data with Native Code]]></title>
            <link>https://blog.stackademic.com/android-ndk-security-protecting-sensitive-data-with-native-code-39ba402bd954?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ba402bd954</guid>
            <category><![CDATA[android-ndk]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Tue, 20 May 2025 17:53:47 GMT</pubDate>
            <atom:updated>2025-05-27T07:28:21.112Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Created by </strong><a href="https://github.com/ChiragVasaniP"><strong>Chirag Vasani </strong></a><strong>| </strong><a href="https://www.linkedin.com/in/chiragkumar-vasani-a5a4a024a/"><strong>LinkedIn</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q9CswKEDrGoAJ2f0" /><figcaption>Photo by <a href="https://unsplash.com/@gamell?utm_source=medium&amp;utm_medium=referral">Joan Gamell</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🔒 Introduction to Android NDK &amp; Why Use It?</h3><p>The <strong>Native Development Kit (NDK)</strong> allows Android developers to write performance-critical parts of their apps in <strong>C/C++</strong> instead of Java/Kotlin. It’s commonly used for:</p><ul><li><strong>Security-sensitive operations</strong> (encryption, anti-tampering, anti-debugging)</li><li><strong>Performance-critical tasks</strong> (game engines, image processing)</li><li><strong>Reusing existing C/C++ libraries</strong></li></ul><p>In this article, we’ll explore how to <strong>secure API keys, URLs, and sensitive logic</strong> using NDK to prevent reverse engineering.</p><h3>🚀 Key Security Features in the Provided Code</h3><p>The provided NDK implementation includes multiple security layers:</p><ol><li><strong>XOR-Encrypted Strings</strong> (API keys, URLs)</li><li><strong>Anti-Tampering Checks</strong> (Signature verification)</li><li><strong>Anti-Debugging &amp; Anti-Frida</strong></li><li><strong>Root Detection</strong></li><li><strong>Whitelisting &amp; Tamper Response</strong></li></ol><h3>🔑 How It Works: Key Functions Explained</h3><h3>1. XOR Encryption for Secure Strings</h3><p>Instead of hardcoding sensitive strings in plaintext, we <strong>XOR-encrypt</strong> them at compile time and decrypt at runtime.</p><h4>Example in Constants.h:</h4><pre>const unsigned char ENCRYPTED_APP_SERVER_URL[] = {<br>    0x32, 0x2E, 0x2E, 0x2A, 0x29, 0x60, 0x75, 0x75,<br>    0x2D, 0x2D, 0x2D, 0x74, 0x3D, 0x35, 0x35, 0x3D,<br>    0x36, 0x3F, 0x74, 0x39, 0x35, 0x37, 0x75<br>};</pre><p><strong>Decryption in </strong>security_utils.cpp<strong>:</strong></p><pre>std::string xorDecrypt(const unsigned char *data, size_t len, char key) {<br>    std::string result;<br>    for (size_t i = 0; i &lt; len; ++i) {<br>        result.push_back(data[i] ^ key); // XOR decryption<br>    }<br>    return result;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MFtSmDo6drVV78_1" /><figcaption>Photo by <a href="https://unsplash.com/@centelm?utm_source=medium&amp;utm_medium=referral">Clément Falize</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>2. Signature Verification (Anti-Tampering)</h3><p>Checks if the APK was signed with the correct key (to prevent repackaging).</p><h4>Key Steps in isCallerValid():</h4><ol><li>Get the app’s signing certificate SHA-256 hash.</li><li>Compare it against <strong>pre-stored trusted hashes</strong> (debug, release, Google Play).</li><li>If mismatched, <strong>force crash</strong> or trigger a security response.</li></ol><pre>bool verifyAppSignature(JNIEnv* env, jobject context) {<br>    return isCallerValid(env, context); // Checks signing cert<br>}</pre><h3>3. Anti-Debugging &amp; Anti-Frida</h3><p>Detects if a debugger or Frida (a dynamic instrumentation tool) is attached.</p><h4>Detecting Debuggers (isDebuggerAttached)</h4><p>Checks /proc/self/status for TracerPid.</p><pre>bool isDebuggerAttached() {<br>    std::ifstream statusFile(&quot;/proc/self/status&quot;);<br>    std::string line;<br>    while (std::getline(statusFile, line)) {<br>        if (line.find(&quot;TracerPid:&quot;) != std::string::npos) {<br>            int tracerPid = std::stoi(line.substr(line.find(&quot;:&quot;) + 1));<br>            return (tracerPid != 0); // If non-zero, debugger is attached<br>        }<br>    }<br>    return false;<br>}</pre><h4>Detecting Frida (detectFrida &amp; checkFridaPorts)</h4><ul><li>Scans /proc for Frida-related processes.</li><li>Checks default Frida ports (27042, 27043).</li></ul><pre>bool detectFrida() {<br>    DIR* dir = opendir(&quot;/proc&quot;);<br>    if (!dir) return false;<br>    // ... (checks for &quot;frida&quot; or &quot;gum-js-loop&quot; in process names)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LWAEa-k0MF5yGrXJ" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>4. Root Detection (isDeviceRooted)</h3><p>Checks for common root files (su, Superuser.apk).</p><pre>bool isDeviceRooted() {<br>    const char* paths[] = {&quot;/sbin/su&quot;, &quot;/system/bin/su&quot;, &quot;/system/xbin/su&quot;};<br>    for (const char* path : paths) {<br>        if (access(path, F_OK) == 0) return true; // File exists → rooted<br>    }<br>    return false;<br>}</pre><h3>📌 How to Integrate This in Your Android App</h3><h3>Step 1: Set Up NDK in build.gradle</h3><pre>android {<br>    defaultConfig {<br>        externalNativeBuild {<br>            cmake {<br>                cppFlags &quot;-std=c++17&quot;<br>                arguments &quot;-DANDROID_STL=c++_shared&quot;<br>            }<br>        }<br>    }<br>    externalNativeBuild {<br>        cmake {<br>            path &quot;CMakeLists.txt&quot;<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U1l9jssurpshm35G" /><figcaption>Photo by <a href="https://unsplash.com/@blakeweyland?utm_source=medium&amp;utm_medium=referral">Blake Weyland</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Step 2: Define JNI Methods in Java/Kotlin</h3><pre>class NativeSecrets {<br>    companion object {<br>        init { System.loadLibrary(&quot;secureapi&quot;) }<br><br>        @JvmStatic external fun getServerUrl(context: Context): String<br>        @JvmStatic external fun getDecryptKey(context: Context): String<br>        @JvmStatic external fun isDeviceRooted(context: Context): Boolean<br>    }<br>}</pre><h3>Step 3: Call Native Functions Safely</h3><pre>val serverUrl = if (!NativeSecrets.isDeviceRooted(this)) {<br>    NativeSecrets.getServerUrl(this)<br>} else {<br>    &quot;&quot; // Block access if rooted<br>}</pre><h3>🚨 Final Thoughts</h3><p>Using <strong>NDK for security</strong> adds a strong layer of protection against common attacks. However:</p><ul><li><strong>No solution is 100% secure</strong> (Obfuscate Java code with ProGuard/R8).</li><li><strong>Update keys periodically</strong> (Rotate encrypted strings).</li><li><strong>Monitor logs</strong> for hacking attempts.</li></ul><p>By combining <strong>NDK security + Java obfuscation + server checks</strong>, you can significantly reduce risks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TWUYWP04NdCL8gRg" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>🔗 Full code available on </strong><a href="https://github.com/ChiragVasaniP/Android_NDK.git"><strong>GitHub</strong></a><br><strong>👨‍💻 Written by </strong><a href="https://www.linkedin.com/in/chiragkumar-vasani-a5a4a024a/"><strong>Chirag Vasani</strong></a></p><h3>👏 Did You Find This Helpful?</h3><p>If you enjoyed this deep dive into <strong>Android NDK security</strong>, smash that <strong>clap button</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8SjfGuGfK-ZH52iK" /><figcaption>Photo by <a href="https://unsplash.com/@amaury_guti?utm_source=medium&amp;utm_medium=referral">Amaury Gutierrez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><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://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=39ba402bd954" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/android-ndk-security-protecting-sensitive-data-with-native-code-39ba402bd954">Android NDK Security: Protecting Sensitive Data with Native Code</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[Mastering Coroutines in Android: Building a Custom Coroutine Scope for Advanced Thread Management…]]></title>
            <link>https://blog.stackademic.com/mastering-coroutines-in-android-building-a-custom-coroutine-scope-for-advanced-thread-management-efbe10e8a458?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/efbe10e8a458</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[custome]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 19:17:15 GMT</pubDate>
            <atom:updated>2024-06-21T05:42:04.134Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Mastering Coroutines in Android: Building a Custom Coroutine Scope for Advanced Thread Management and UI Safety</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*9UfWHZzkng14RGXh.png" /><figcaption>Efficient Coroutine Management with CustomCoroutineScope in Android</figcaption></figure><p>Coroutines in Kotlin provide a powerful way to manage asynchronous tasks, but handling them efficiently in Android applications requires careful consideration of threading and lifecycle management. In this article, we explore how to create and utilize a CustomCoroutineScope class that enhances coroutine management, error handling, and ensures safe UI updates on the main thread.</p><h3>Understanding CustomCoroutineScope</h3><p>The CustomCoroutineScope class extends CoroutineScope and offers advanced features for managing coroutines within an Android application. It provides:</p><ul><li><strong>Thread Management</strong>: Dynamically manages a custom thread for coroutine execution based on runtime conditions like memory usage.</li><li><strong>Error Handling</strong>: Includes a custom exception handler to manage and log exceptions occurring within coroutines.</li><li><strong>Main Thread Safety</strong>: Ensures all UI-related operations are executed on the main thread to comply with Android’s UI thread requirements.</li></ul><h3>Implementation Details</h3><p>Let’s delve into the key components and methods of CustomCoroutineScope:</p><h4>1. Initialization and Context Setup</h4><pre>class CustomCoroutineScope : CoroutineScope { <br>   private var job: Job = Job() // Manages all coroutines in this scope<br>    private var dispatcher: CoroutineDispatcher = Dispatchers.Default // Default dispatcher<br>    private var customThread: Thread? = null // Custom thread for the scope<br>    private var customHandler: CoroutineExceptionHandler? = null // Custom exception handler<br>    private val mainDispatcher = Dispatchers.Main // Main dispatcher for UI operations<br>    // Example memory threshold in MB<br>    private val memoryThresholdMb = 100<br>    ...<br>}</pre><ul><li><strong>Job</strong>: Manages the lifecycle of all coroutines launched within the scope.</li><li><strong>CoroutineContext</strong>: Combines the dispatcher (Dispatchers.Default by default) and the job.</li><li><strong>Custom Thread and Handler</strong>: Manages a dedicated thread (customThread) with its Looper and CoroutineExceptionHandler (customHandler) for error management.</li></ul><h4>2. Coroutine Launching and Error Handling</h4><pre>/**<br>     * Launches a coroutine in this scope with error handling and completion callback.<br>     */<br>    fun launchCustom(<br>        block: suspend CoroutineScope.() -&gt; Unit,<br>        onError: ((Throwable) -&gt; Unit)? = null,<br>        onComplete: (() -&gt; Unit)? = null<br>    ): Job {<br>        return launch {<br>            try {<br>                block()<br>                onComplete?.invoke()<br>            } catch (e: Throwable) {<br>                onError?.invoke(e)<br>            }<br>        }<br>    }</pre><ul><li><strong>launchCustom</strong>: Launches a coroutine with provided block of code. Handles errors (onError) and invokes completion callback (onComplete) upon successful execution.</li></ul><h4>3. Thread Management and Dynamic Creation</h4><pre>/**<br>     * Determines if a new custom thread should be created based on a memory usage threshold.<br>     */<br>    private fun shouldCreateNewThread(): Boolean {<br>        val memoryInfo = Runtime.getRuntime().freeMemory() / (1024 * 1024) // Convert to MB<br>        return memoryInfo &lt; memoryThresholdMb<br>    }   <br> /**<br>     * Creates a new custom thread if necessary.<br>     */<br>    private fun createCustomThreadIfNeeded() {<br>        if (customThread == null || !customThread!!.isAlive) {<br>            customThread = Thread {<br>                Looper.prepare()<br>                customHandler = CoroutineExceptionHandler { _, throwable -&gt;<br>                    // Handle exceptions here (e.g., log, report, etc.)<br>                    println(&quot;Coroutine Exception on Custom Thread: $throwable&quot;)<br>                }<br>                dispatcher = customHandler!! + Dispatchers.Default<br>                Looper.loop()<br>            }<br>            customThread!!.start()<br>        }<br>    }</pre><ul><li><strong>shouldCreateNewThread</strong>: Checks if a new custom thread should be created based on the current memory usage (memoryThresholdMb). Adjust this condition according to specific memory management needs.</li><li><strong>createCustomThreadIfNeeded</strong>: Creates a new custom thread if none exists or if the existing thread is no longer alive. Sets up Looper for message handling and CoroutineExceptionHandler for error management.</li></ul><h4>4. Automatic Thread Management with launchAutoManage</h4><pre>/**<br>     * Launches a coroutine with automatic thread management.<br>     * Ensures UI updates are executed on the main thread.<br>     */<br>    fun launchAutoManage(<br>        block: suspend CoroutineScope.() -&gt; Unit,<br>        onError: ((Throwable) -&gt; Unit)? = null,<br>        onComplete: (() -&gt; Unit)? = null<br>    ): Job {<br>        return launch {<br>            if (shouldCreateNewThread()) {<br>                createCustomThreadIfNeeded()<br>            }<br>            try {<br>                block()<br>                // Ensure UI updates are on the main thread<br>                withContext(mainDispatcher) {<br>                    onComplete?.invoke()<br>                }<br>            } catch (e: Throwable) {<br>                // Handle exceptions on the main thread<br>                withContext(mainDispatcher) {<br>                    onError?.invoke(e)<br>                }<br>            }<br>        }<br>    }</pre><ul><li><strong>launchAutoManage</strong>: Automates thread management based on runtime conditions (shouldCreateNewThread). Executes the coroutine block, ensures UI updates (onComplete) occur on the main thread (mainDispatcher), and handles errors (onError) safely.</li></ul><h3>Usage Example</h3><pre>fun main() {<br>    val customScope = CustomCoroutineScope()   <br> // Example usage of launchAutoManage<br>    customScope.launchAutoManage(<br>        block = {<br>            println(&quot;Running coroutine with automatic thread management&quot;)<br>            delay(1000)<br>            // Simulate updating UI (replace with actual UI update code in Android)<br>            withContext(Dispatchers.Main) {<br>                println(&quot;Coroutine completed&quot;)<br>            }<br>        },<br>        onError = { throwable -&gt;<br>            println(&quot;Coroutine error: $throwable&quot;)<br>        },<br>        onComplete = {<br>            println(&quot;Coroutine execution finished&quot;)<br>        }<br>    )<br>Thread.sleep(2000) // Keep the program alive to complete coroutine execution<br>    customScope.cancel() // Cancel the scope and all coroutines<br>}</pre><p>The CustomCoroutineScope class exemplifies efficient coroutine management in Android applications, ensuring optimal performance, error resilience, and safe UI interactions. By leveraging custom thread management and main thread handling, developers can streamline asynchronous operations and enhance overall application stability.</p><p>Implementing CustomCoroutineScope not only improves code organization but also facilitates robust coroutine execution tailored to specific application requirements. Integrate it into your Android projects to harness the full potential of Kotlin coroutines while adhering to best practices in concurrency and UI thread management.</p><h3>Conclusion</h3><p>The CustomCoroutineScope class represents a robust solution for managing coroutines in Android applications, offering advanced features for thread management, error handling, and ensuring UI updates on the main thread. Developed with insights from ChatGPT and meticulous coding by Chirag Kumar Vasani, this class exemplifies the synergy between human creativity and AI assistance in software development.</p><p>For the full implementation and further exploration, visit the <a href="https://github.com/ChiragVasaniP/CustomCoroutineScope">GitHub repository</a>. Connect with Chirag Kumar Vasani on <a href="https://www.linkedin.com/in/chiragkumar-vasani-a5a4a024a/">LinkedIn</a> and show your appreciation by clapping if you found this article helpful.</p><p>Thanks for reading and 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></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>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=efbe10e8a458" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-coroutines-in-android-building-a-custom-coroutine-scope-for-advanced-thread-management-efbe10e8a458">Mastering Coroutines in Android: Building a Custom Coroutine Scope for Advanced Thread Management…</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[Tic-Tac-Toe: Unbeatable AI for Android]]></title>
            <link>https://blog.stackademic.com/tic-tac-toe-unbeatable-ai-for-android-c86a0d9a970e?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/c86a0d9a970e</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Wed, 08 May 2024 14:17:19 GMT</pubDate>
            <atom:updated>2024-05-09T00:09:09.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*qV4AEPQcZkjwISiE" /></figure><p><strong>Introduction:</strong></p><p>Welcome to the world of Tic-Tac-Toe, where Xs and Os battle it out for supremacy on a 3x3 grid. But this isn’t your ordinary game; we’re diving deep into the realm of AI development to create an opponent that’s not just formidable but downright hilarious. Join us on a journey through code as we unveil the secrets behind building an unbeatable Tic-Tac-Toe AI in Kotlin.</p><pre>// Importing necessary packages<br>package com.dac.tictactoe.ai<br><br>// Defining the HardAI class<br>class HardAI {<br><br>    internal var player = &#39;x&#39;<br>    internal var opponent = &#39;o&#39;<br><br>    internal inner class Move(var row: Int, var col: Int)<br><br>    internal fun isMovesLeft(board: Array&lt;CharArray&gt;): Boolean {<br>        for (i in 0..2)<br>            for (j in 0..2)<br>                if (board[i][j] == &#39;_&#39;)<br>                    return true<br>        return false<br>    }<br>    // Evaluation function<br>    private fun evaluate(board: Array&lt;CharArray&gt;, symbol: Char): Int {<br>        var score = 0<br><br>        // Check for potential wins or blocks for the player<br>        for (row in 0 until 3) {<br>            val rowOccupiedByPlayer = (0 until 3).all { board[row][it] == player }<br>            if (rowOccupiedByPlayer) {<br>                score -= 100 // Player has a winning possibility<br>            }<br><br>            val rowOccupiedByOpponent = (0 until 3).all { board[row][it] == opponent }<br>            if (rowOccupiedByOpponent) {<br>                score += 100 // AI has a winning possibility<br>            }<br>        }<br><br>        for (col in 0 until 3) {<br>            val colOccupiedByPlayer = (0 until 3).all { board[it][col] == player }<br>            if (colOccupiedByPlayer) {<br>                score -= 100 // Player has a winning possibility<br>            }<br><br>            val colOccupiedByOpponent = (0 until 3).all { board[it][col] == opponent }<br>            if (colOccupiedByOpponent) {<br>                score += 100 // AI has a winning possibility<br>            }<br>        }<br><br>        val mainDiagonalOccupiedByPlayer = (0 until 3).all { board[it][it] == player }<br>        if (mainDiagonalOccupiedByPlayer) {<br>            score -= 100 // Player has a winning possibility<br>        }<br><br>        val mainDiagonalOccupiedByOpponent = (0 until 3).all { board[it][it] == opponent }<br>        if (mainDiagonalOccupiedByOpponent) {<br>            score += 100 // AI has a winning possibility<br>        }<br><br>        val antiDiagonalOccupiedByPlayer = (0 until 3).all { board[it][2 - it] == player }<br>        if (antiDiagonalOccupiedByPlayer) {<br>            score -= 100 // Player has a winning possibility<br>        }<br><br>        val antiDiagonalOccupiedByOpponent = (0 until 3).all { board[it][2 - it] == opponent }<br>        if (antiDiagonalOccupiedByOpponent) {<br>            score += 100 // AI has a winning possibility<br>        }<br><br>        // Additional evaluation factors<br>        // Center control<br>        if (board[1][1] == symbol) {<br>            score += 10<br>        }<br>        // Corner control<br>        if (board[0][0] == symbol || board[0][2] == symbol || board[2][0] == symbol || board[2][2] == symbol) {<br>            score += 5<br>        }<br>        // Edge control<br>        if (board[0][1] == symbol || board[1][0] == symbol || board[1][2] == symbol || board[2][1] == symbol) {<br>            score += 3<br>        }<br><br>        return score<br>    }<br>    // Minimax algorithm implementation<br>    internal fun minimax(board: Array&lt;CharArray&gt;, depth: Int, isMax: Boolean): Int {<br>        val score = evaluate(board, player)<br><br>        if (score == 100 || score == -100)<br>            return score<br><br>        if (!isMovesLeft(board) || depth == 4) // Increased depth for deeper search<br>            return 0<br><br>        var bestVal = if (isMax) Int.MIN_VALUE else Int.MAX_VALUE<br><br>        for (i in 0 until 3) {<br>            for (j in 0 until 3) {<br>                if (board[i][j] == &#39;_&#39;) {<br>                    if (isMax) {<br>                        board[i][j] = player<br>                        bestVal = maxOf(bestVal, minimax(board, depth + 1, !isMax))<br>                    } else {<br>                        board[i][j] = opponent<br>                        bestVal = minOf(bestVal, minimax(board, depth + 1, !isMax))<br>                    }<br>                    board[i][j] = &#39;_&#39;<br>                }<br>            }<br>        }<br><br>        return bestVal<br>    }<br>    // Finding the best move<br>    internal fun findBestMove(board: Array&lt;CharArray&gt;): Int {<br>        // Check if AI has a winning possibility and prioritize it<br>        for (i in 0 until 3) {<br>            for (j in 0 until 3) {<br>                if (board[i][j] == &#39;_&#39;) {<br>                    board[i][j] = opponent<br>                    if (evaluate(board, opponent) == 100) {<br>                        board[i][j] = &#39;_&#39;<br>                        return i * 3 + j + 1<br>                    }<br>                    board[i][j] = &#39;_&#39;<br>                }<br>            }<br>        }<br><br>        // If AI doesn&#39;t have a winning possibility, defend against the player<br>        for (i in 0 until 3) {<br>            for (j in 0 until 3) {<br>                if (board[i][j] == &#39;_&#39;) {<br>                    board[i][j] = player<br>                    if (evaluate(board, player) == -100) {<br>                        board[i][j] = &#39;_&#39;<br>                        return i * 3 + j + 1<br>                    }<br>                    board[i][j] = &#39;_&#39;<br>                }<br>            }<br>        }<br><br>        // If neither player nor AI has a high chance to win, find the best move for the AI<br>        var bestVal = Int.MIN_VALUE<br>        var bestMove = -1<br><br>        for (i in 0 until 3) {<br>            for (j in 0 until 3) {<br>                if (board[i][j] == &#39;_&#39;) {<br>                    board[i][j] = player<br>                    val moveVal = minimax(board, 0, false)<br>                    board[i][j] = &#39;_&#39;<br>                    if (moveVal &gt; bestVal) {<br>                        bestVal = moveVal<br>                        bestMove = i * 3 + j + 1<br>                    }<br>                }<br>            }<br>        }<br><br>        return bestMove<br>    }<br>    // Constructing the game board<br>    internal fun constructBoard(player1: MutableList&lt;Int&gt;, comp: MutableList&lt;Int&gt;): Int {<br>        val board = Array(3) { CharArray(3) }<br>        if (player1.isEmpty() &amp;&amp; comp.isEmpty()) {<br>            // If both player1 and comp lists are empty, choose a random position<br>            val randomPosition = (1..9).random()<br>            return randomPosition<br>        }<br>        for (cellId in 1..9) {<br>            if (player1.contains(cellId)) {<br>                when (cellId) {<br>                    1 -&gt; board[0][0] = &#39;x&#39;<br>                    2 -&gt; board[0][1] = &#39;x&#39;<br>                    3 -&gt; board[0][2] = &#39;x&#39;<br>                    4 -&gt; board[1][0] = &#39;x&#39;<br>                    5 -&gt; board[1][1] = &#39;x&#39;<br>                    6 -&gt; board[1][2] = &#39;x&#39;<br>                    7 -&gt; board[2][0] = &#39;x&#39;<br>                    8 -&gt; board[2][1] = &#39;x&#39;<br>                    9 -&gt; board[2][2] = &#39;x&#39;<br>                }<br>            } else if (comp.contains(cellId)) {<br>                when (cellId) {<br>                    1 -&gt; board[0][0] = &#39;o&#39;<br>                    2 -&gt; board[0][1] = &#39;o&#39;<br>                    3 -&gt; board[0][2] = &#39;o&#39;<br>                    4 -&gt; board[1][0] = &#39;o&#39;<br>                    5 -&gt; board[1][1] = &#39;o&#39;<br>                    6 -&gt; board[1][2] = &#39;o&#39;<br>                    7 -&gt; board[2][0] = &#39;o&#39;<br>                    8 -&gt; board[2][1] = &#39;o&#39;<br>                    9 -&gt; board[2][2] = &#39;o&#39;<br>                }<br>            } else {<br>                when (cellId) {<br>                    1 -&gt; board[0][0] = &#39;_&#39;<br>                    2 -&gt; board[0][1] = &#39;_&#39;<br>                    3 -&gt; board[0][2] = &#39;_&#39;<br>                    4 -&gt; board[1][0] = &#39;_&#39;<br>                    5 -&gt; board[1][1] = &#39;_&#39;<br>                    6 -&gt; board[1][2] = &#39;_&#39;<br>                    7 -&gt; board[2][0] = &#39;_&#39;<br>                    8 -&gt; board[2][1] = &#39;_&#39;<br>                    9 -&gt; board[2][2] = &#39;_&#39;<br>                }<br>            }<br>        }<br>        return findBestMove(board)<br>    }<br>}</pre><p><strong>Visual Presentation</strong>: Now, let’s dive into the code and uncover the magic behind our Tic-Tac-Toe AI. First, we define the HardAI class, which encapsulates all the intelligence needed to play the game.</p><p><strong>Explanation:</strong></p><ul><li>The code begins by importing necessary packages and declaring the HardAI class.</li><li>We initialize variables for the player and opponent symbols (‘x’ and ‘o’ respectively) and define an inner class Move to represent a move on the game board.</li><li>The isMovesLeft function checks if there are any empty cells left on the board.</li><li>Next, we implement the evaluation function to assess the current state of the board and assign scores based on potential wins, blocks, and positional advantages.</li><li>The Minimax algorithm is then implemented to recursively evaluate possible moves and select the best one.</li><li>The findBestMove function orchestrates the AI&#39;s decision-making process, prioritizing winning moves, blocking opponent victories, and strategizing for optimal gameplay.</li><li>Lastly, the constructBoard function converts player and AI move lists into a game board representation and selects the best move for the AI.</li></ul><p><strong>Let’s break down the algorithm used in the HardAI class step by step:</strong></p><ol><li><strong>Evaluation Function:</strong></li></ol><ul><li>The evaluate function analyzes the current state of the Tic-Tac-Toe board and assigns a score based on various factors.</li><li>It checks for potential wins or blocks for both the player and the AI by examining rows, columns, and diagonals.</li><li>Additionally, it considers positional advantages such as control of the center, corners, and edges of the board.</li><li>The evaluation function aims to quantify the desirability of a given board configuration for the AI.</li></ul><ol><li><strong>Minimax Algorithm:</strong></li></ol><ul><li>The minimax algorithm is a decision-making technique commonly used in two-player games to determine the optimal move for a player.</li><li>It operates recursively, considering all possible future moves and their outcomes while assuming that both players will make the best possible moves.</li><li>In the context of Tic-Tac-Toe, the minimax algorithm evaluates each possible move by the AI and the player, recursively exploring the game tree until reaching a terminal state (win, lose, or draw).</li><li>The algorithm assigns scores to terminal states (win: +100, lose: -100, draw: 0) and propagates these scores back up the tree to determine the best move for the AI.</li><li>By maximizing the AI’s score and minimizing the opponent’s score at each level of recursion, the algorithm selects the move that maximizes the AI’s chances of winning.</li></ul><ol><li><strong>Finding the Best Move:</strong></li></ol><ul><li>The findBestMove function orchestrates the AI&#39;s decision-making process by considering various factors.</li><li>It first checks if the AI has a winning possibility and prioritizes such moves to secure victory.</li><li>If the AI doesn’t have a winning possibility, it focuses on blocking the opponent from winning by defending against their potential winning moves.</li><li>If neither player nor AI has a high chance to win immediately, the function uses the minimax algorithm to find the best move for the AI.</li><li>The AI iterates over all empty cells on the board, simulates placing its symbol in each cell, evaluates the resulting board configuration using the minimax algorithm, and selects the move with the highest score.</li></ul><p>In summary, the HardAI class employs the minimax algorithm coupled with an evaluation function to make strategic decisions in Tic-Tac-Toe. By analyzing the current state of the board and recursively exploring possible future moves, the AI aims to outsmart its opponent and secure victory while maintaining a sense of humor throughout the game.</p><p><a href="https://github.com/ChiragVasaniP/Tic-Toc-Toe-AI/blob/main/HardAi.kt"><strong>Git Link</strong></a></p><p><strong>Conclusion</strong>: With our Tic-Tac-Toe AI’s inner workings laid bare, it’s time to put it to the test! Armed with humor and strategic prowess, our AI is ready to take on any challenger in the ultimate game of Xs and Os. Are you up for the challenge? Let the games begin!</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>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>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=c86a0d9a970e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/tic-tac-toe-unbeatable-ai-for-android-c86a0d9a970e">Tic-Tac-Toe: Unbeatable AI for 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[Organizing Your Android App with MVVM: A Package Hierarchy Guide]]></title>
            <link>https://blog.stackademic.com/organizing-your-android-app-with-mvvm-a-package-hierarchy-guide-c1c0f48fba60?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1c0f48fba60</guid>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Sun, 21 Apr 2024 08:49:40 GMT</pubDate>
            <atom:updated>2024-04-23T00:23:36.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*pq3hUneWWWsLeCoO.png" /></figure><p>In the world of Android development, structuring your application code effectively is crucial for maintainability, scalability, and overall code quality. One popular architecture pattern that has gained significant traction in recent years is the Model-View-ViewModel (MVVM) pattern. MVVM provides a clear separation of concerns, making it easier to manage complex UI logic and data interactions. In this article, we’ll explore how to organize your Android app using MVVM with a well-defined package hierarchy.</p><h3>Understanding MVVM</h3><p>Before diving into the package structure, let’s briefly review the MVVM architecture pattern:</p><ul><li>Model: Represents the data and business logic of the application. This can include data models, repositories, and data access layers.</li><li>View: Represents the UI components visible to the user. In Android, views are typically Activities, Fragments, custom Views, or XML layout files.</li><li>ViewModel: Acts as an intermediary between the View and the Model. ViewModels hold and manage UI-related data and handle user interactions. They are lifecycle-aware components that survive configuration changes, such as screen rotations.</li></ul><h3>Package Hierarchy</h3><p>To maintain a clean and organized codebase, it’s essential to establish a consistent package hierarchy. Here’s a suggested package structure for an Android app following the MVVM architecture:</p><ol><li>model: This package contains all the data models and entities used in the application. These classes represent the structure of the data managed by the app.</li><li>view: The view package houses all UI-related components, including Activities, Fragments, custom Views, and Adapters. Each UI component should be responsible for displaying data and handling user interactions.</li><li>viewmodel: The viewmodel package contains ViewModel classes responsible for managing UI-related data and handling user interactions. Each ViewModel typically corresponds to a specific UI component (Activity or Fragment).</li><li>repository: This package contains classes responsible for managing data operations. Repositories abstract the data sources (such as databases, web services, or local files) from the rest of the application and provide a clean API for accessing and modifying data.</li><li>di (dependency injection): Dependency injection frameworks like Dagger or Hilt are commonly used in Android development to manage dependencies between different components of the application. The di package contains classes related to dependency injection setup.</li><li>util: This package contains utility classes and helper methods used throughout the application. These can include converters, validators, date/time utilities, and other commonly used functionalities.</li><li>network: The network package contains classes related to network operations, such as API clients, request/response models, and network-related utilities.</li><li>database: The database package contains classes related to local database operations. This includes database clients, entities, DAOs (Data Access Objects), and database-related utilities.</li></ol><h3>Benefits of a Well-Organized Package Hierarchy</h3><p>Establishing a clear package hierarchy based on the MVVM architecture offers several benefits:</p><ul><li>Separation of Concerns: Each package represents a specific layer or component of the application, making it easier to understand and maintain the codebase.</li><li>Modularity: Components are organized into separate packages, allowing for easier module-level testing and reusability.</li><li>Scalability: As the application grows, the well-defined package structure facilitates the addition of new features and components without introducing complexity.</li><li>Collaboration: A consistent package hierarchy enables better collaboration among team members, as everyone follows the same conventions and structure.</li></ul><pre>com<br>└── example<br>    └── myapplication<br>        ├── model<br>        │   ├── User.java<br>        │   └── Product.java<br>        │<br>        ├── view<br>        │   ├── MainActivity.java<br>        │   ├── ProductFragment.java<br>        │   └── adapters<br>        │       └── ProductAdapter.java<br>        │<br>        ├── viewmodel<br>        │   ├── MainViewModel.java<br>        │   └── ProductViewModel.java<br>        │<br>        ├── repository<br>        │   ├── UserRepository.java<br>        │   └── ProductRepository.java<br>        │<br>        ├── di<br>        │   ├── AppComponent.java<br>        │   ├── AppModule.java<br>        │   └── DaggerAppComponent.java<br>        │<br>        ├── util<br>        │   └── DateUtils.java<br>        │<br>        ├── network<br>        │   ├── ApiService.java<br>        │   └── RetrofitClient.java<br>        │<br>        └── database<br>            ├── AppDatabase.java<br>            ├── UserDao.java<br>            └── ProductDao.java</pre><h3>Conclusion</h3><p>Organizing your Android application using the MVVM architecture pattern with a well-defined package hierarchy is essential for building maintainable, scalable, and high-quality apps. By following the suggested package structure outlined in this article, you can ensure that your codebase remains clean, modular, and easy to maintain throughout the development lifecycle.</p><p>In summary, embrace the principles of MVVM and leverage a well-organized package hierarchy to create robust and elegant Android applications.</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=c1c0f48fba60" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/organizing-your-android-app-with-mvvm-a-package-hierarchy-guide-c1c0f48fba60">Organizing Your Android App with MVVM: A Package Hierarchy Guide</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[LiveData in Android: A Deep Dive with Examples]]></title>
            <link>https://blog.stackademic.com/livedata-in-android-a-deep-dive-with-examples-f3bae0951721?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3bae0951721</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 09:33:57 GMT</pubDate>
            <atom:updated>2024-06-17T01:13:33.089Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U_O9u7ZUMlX0uSyh" /></figure><p>LiveData is a cornerstone of modern Android development, simplifying data flow and ensuring a responsive UI. This article delves into the intricacies of LiveData, providing a comprehensive understanding of its features, benefits, and best practices, along with illustrative examples.</p><p><strong>Conceptual Understanding:</strong></p><ul><li><strong>Problem:</strong> Traditionally, managing data flow between activities, fragments, and the UI in Android could be cumbersome. Manual data updates and potential lifecycle issues often led to stale data and crashes.</li><li><strong>Solution:</strong> LiveData addresses these challenges by providing an observable data holder class. It offers lifecycle awareness, data observation, and thread safety, streamlining data handling in your applications.</li></ul><p><strong>Key Features of LiveData:</strong></p><ul><li><strong>Lifecycle Awareness:</strong> LiveData is lifecycle-aware. It only delivers updates to active observers (activities or fragments that are in STARTED or RESUMED states). This prevents data leaks and ensures your UI reflects changes only when visible.</li><li><strong>Data Observation:</strong> LiveData enables you to observe variations in the data it holds. Observers (activities or fragments) can register themselves to be notified whenever the data value changes. This fosters a reactive approach where your UI automatically adapts to the latest data.</li><li><strong>Thread Safety:</strong> LiveData guarantees thread safety by handling data updates on the main thread. This eliminates UI thread crashes that could arise from background operations updating the data directly.</li></ul><p><strong>Types of LiveData:</strong></p><ol><li><strong>MutableLiveData:</strong> This is the most common type of LiveData. It’s mutable, allowing you to directly modify the held value using setValue(T value). It&#39;s suitable for scenarios where you have control over the data and need to update it programmatically.</li><li><strong>Immutable LiveData:</strong> While not a direct subclass of LiveData, you can achieve immutability by wrapping your data in an immutable class or using libraries like LiveData KTX that provide immutable LiveData builders. This promotes a more functional approach and avoids accidental data modifications.</li></ol><p><strong>Implementation Details:</strong></p><ul><li><strong>LiveData Class:</strong> The foundation of LiveData is the LiveData class. However, you typically use its subclass - MutableLiveData. MutableLiveData allows you to directly modify the held value.</li><li><strong>Observers:</strong> Observers are interfaces (like Observer or LifecycleObserver) that define how components react to data changes. They implement methods like onChanged(T value) to handle updates.</li><li><strong>LifecycleOwner:</strong> The component observing the LiveData (usually an activity or fragment) is the LifecycleOwner. It provides lifecycle information to LiveData for awareness.</li></ul><p><strong>Setting Data Values:</strong></p><ul><li>setValue(T value)<strong>:</strong> Use this method to directly set the value of the LiveData on the main thread. This triggers immediate notification to all active observers.</li><li>postValue(T value)<strong>:</strong> If updating the LiveData from a background thread, use postValue. It safely posts the update to the main thread and then notifies observers.</li></ul><p><strong>Best Practices:</strong></p><ul><li><strong>Observe on Main Thread:</strong> Always observe LiveData changes on the main thread to avoid crashes. Use observe within activity/fragment lifecycle methods (like onCreate or onStart).</li><li><strong>Unregister Observers:</strong> When an activity/fragment is destroyed, unregister observers using removeObserver to prevent memory leaks. Consider using lifecycle-aware components like ViewModel and automatic observer registration for simpler management.</li><li><strong>Error Handling:</strong> LiveData itself doesn&#39;t handle errors. Consider wrapper classes or custom LiveData implementations that incorporate error handling if needed.</li></ul><p><strong>Advanced Topics:</strong></p><ul><li><strong>Transformations:</strong> LiveData supports transformations using Transformations. You can create a new LiveData based on the value of another LiveData, applying logic or computation.</li><li><strong>SwitchMap:</strong> This operator within LiveData is useful for handling chains of network requests. It switches to a new LiveData based on the emissions from a previous LiveData.</li><li><strong>MediatorLiveData:</strong> This subclass allows you to combine multiple LiveData sources into a single LiveData stream. It&#39;s helpful for complex data dependencies.</li></ul><p><strong>Benefits of Using LiveData:</strong></p><ul><li><strong>Simplified Data Flow:</strong> LiveData streamlines data communication between UI components and data sources.</li><li><strong>Improved UI Responsiveness:</strong> Reactive UI updates based on data changes enhance user experience.</li><li><strong>Reduced Boilerplate Code:</strong> Less manual code is needed for handling lifecycle awareness and data updates, leading to cleaner code.</li><li><strong>Crash Prevention:</strong> Thread safety ensures a more robust application, preventing UI thread crashes.</li></ul><p><strong>Example:</strong></p><pre>// In your ViewModel<br>class MyViewModel : ViewModel() {<br>    private val _data = MutableLiveData&lt;String&gt;()<br><br>    val data: LiveData&lt;String&gt;<br>        get() = _data<br><br>    fun fetchData() {<br>        // Simulate network call<br>        Thread {<br>            val data = fetchFromNetwork()<br>            _data.postValue(data) // Update LiveData on main thread<br>        }.start()<br>    }<br>}<br><br>// In your Activity<br>myViewModel.fetchData()<br>myViewModel.data.observe(this, Observer { value -&gt;<br>    // Update your UI with the new data value<br>    textView.text = value<br>})</pre><p>I hope this comprehensive explanation, incorporating best practices and clear examples, proves helpful in your Android development endeavors!</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></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>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=f3bae0951721" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/livedata-in-android-a-deep-dive-with-examples-f3bae0951721">LiveData in Android: A Deep Dive with Examples</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[Jetpack Compose: A Comprehensive Guide to UI Development]]></title>
            <link>https://blog.stackademic.com/jetpack-compose-a-comprehensive-guide-to-ui-development-904f977e31fb?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/904f977e31fb</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 16:52:25 GMT</pubDate>
            <atom:updated>2024-05-08T00:59:17.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7u9HtSQzJIy4WHmNDEjwg.png" /></figure><p>In the dynamic world of Android app development, Jetpack Compose emerges as a transformative toolkit, simplifying UI development and boosting productivity. Let’s delve into the intricacies of Jetpack Compose, exploring its wide array of widgets and tools for crafting stunning user interfaces.</p><h3>Understanding Jetpack Compose</h3><p>Jetpack Compose is a modern UI toolkit for building native Android applications. Unlike traditional Android UI development with XML layouts, Compose adopts a declarative approach, where UI components are described as functions that produce UI elements. This paradigm shift enhances developer productivity and facilitates the creation of complex and dynamic user interfaces.</p><h3>Widgets in Jetpack Compose</h3><p>Jetpack Compose provides a rich set of widgets (or composables) that cover various UI needs. Here’s a detailed look at some of the key widgets:</p><h4>1. Text</h4><ul><li>Text(): Renders a piece of text with customizable styling options such as font size, color, and alignment.</li></ul><h4>2. Buttons</h4><ul><li>Button(): Represents a clickable button with customizable text and styling.</li><li>IconButton(): Renders an icon button with optional text and custom iconography.</li></ul><h4>3. Input Fields</h4><ul><li>TextField(): Displays an editable text field for user input, with support for keyboard actions and validation.</li></ul><h4>4. Lists and Grids</h4><ul><li>LazyColumn(): Renders a vertically scrolling list of items efficiently, loading only the visible items for optimal performance.</li><li>LazyRow(): Displays a horizontally scrolling list of items.</li><li>Grid(): Arranges items in a grid layout with customizable column count and item spacing.</li></ul><h4>5. Images</h4><ul><li>Image(): Loads and displays images from various sources, with support for placeholder content and content scale types.</li></ul><h4>6. Layouts</h4><ul><li>Column(): Arranges child elements vertically in a column layout.</li><li>Row(): Organizes child elements horizontally in a row layout.</li><li>Box(): Positions child elements relative to each other, allowing for complex layouts and overlays.</li></ul><h4>7. Navigation</h4><ul><li>NavHost(): Defines a navigation host for managing navigation within an app.</li><li>NavController(): Handles navigation actions and destinations within a navigation graph.</li></ul><h4>8. Material Components</h4><ul><li>TopAppBar(): Displays a Material Design app bar at the top of the screen.</li><li>BottomAppBar(): Presents a Material Design bottom app bar for navigation and actions.</li><li>Card(): Represents a Material Design card for displaying content with elevation and rounded corners.</li></ul><h3>State Management and Interactivity</h3><p>Jetpack Compose offers robust tools for managing UI state and handling user interactions:</p><ul><li>State: Compose provides state objects that trigger UI updates when modified, ensuring a reactive and responsive user interface.</li><li>ViewModels: Integration with ViewModel architecture component enables separation of UI logic from data management, enhancing code organization and testability.</li><li>Gesture Detection: Compose offers built-in support for gesture detection, allowing developers to capture touch events and implement custom interactions with ease.</li></ul><h3>Material Design Integration</h3><p>Jetpack Compose seamlessly integrates with Material Design, offering a wide range of pre-designed components and styling options. Developers can leverage Material Design guidelines to create visually appealing and consistent user interfaces across different Android devices and versions.</p><h3>Tooling and Integration</h3><p>Jetpack Compose is fully integrated with Android Studio, providing developers with powerful tools for UI design, debugging, and testing:</p><ul><li>Live Previews: Instantly preview UI changes in real-time, speeding up the design iteration process.</li><li>Interactive Previews: Interact with UI components directly within the IDE, simulating user interactions and behavior.</li><li>Layout Inspectors: Analyze and debug UI layouts to identify issues and optimize performance.</li></ul><p>Certainly! Let’s explore Jetpack Compose with examples for each widget mentioned:</p><h3>1. Text</h3><pre>import androidx.compose.foundation.Text<br>import androidx.compose.runtime.Composable<br>@Composable<br>fun MyText() {<br>    Text(text = &quot;Hello, Jetpack Compose!&quot;)<br>}</pre><h3>2. Button</h3><pre>import androidx.compose.foundation.Button<br>import androidx.compose.runtime.Composable<br>@Composable<br>fun MyButton() {<br>    Button(onClick = { /* Do something */ }) {<br>        Text(text = &quot;Click Me&quot;)<br>    }<br>}</pre><h3>3. Input Fields</h3><pre>import androidx.compose.foundation.TextField<br>import androidx.compose.runtime.mutableStateOf<br>import androidx.compose.runtime.remember<br>import androidx.compose.runtime.Composable<br>@Composable<br>fun MyTextField() {<br>    val textState = remember { mutableStateOf(&quot;&quot;) }<br>    TextField(<br>        value = textState.value,<br>        onValueChange = { textState.value = it },<br>        label = { Text(&quot;Enter text&quot;) }<br>    )<br>}</pre><h3>4. Lists and Grids</h3><pre>import androidx.compose.foundation.lazy.LazyColumn<br>import androidx.compose.runtime.Composable<br>@Composable<br>fun MyList() {<br>    val items = listOf(&quot;Item 1&quot;, &quot;Item 2&quot;, &quot;Item 3&quot;)<br>    LazyColumn {<br>        items(items) { item -&gt;<br>            Text(text = item)<br>        }<br>    }<br>}</pre><h3>5. Images</h3><pre>import androidx.compose.foundation.Image<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.res.painterResource<br>@Composable<br>fun MyImage() {<br>    Image(<br>        painter = painterResource(id = R.drawable.my_image),<br>        contentDescription = &quot;My Image&quot;<br>    )<br>}</pre><h3>6. Layouts</h3><pre>import androidx.compose.foundation.layout.Column<br>import androidx.compose.runtime.Composable<br>@Composable<br>fun MyColumnLayout() {<br>    Column {<br>        Text(&quot;Item 1&quot;)<br>        Text(&quot;Item 2&quot;)<br>        Text(&quot;Item 3&quot;)<br>    }<br>}</pre><h3>7. Navigation</h3><pre>import androidx.compose.material.NavHost<br>import androidx.compose.runtime.Composable<br>@Composable<br>fun MyNavigation() {<br>    NavHost(/* Define navigation destinations */)<br>}</pre><h3>8. Material Components</h3><pre>import androidx.compose.material.TopAppBar<br>import androidx.compose.runtime.Composable<br>@Composable<br>fun MyTopAppBar() {<br>    TopAppBar(title = { Text(&quot;My App&quot;) })<br>}</pre><p>These examples illustrate the usage of various Jetpack Compose widgets in creating different components of a UI. You can further customize and extend these examples based on your specific requirements.</p><h3>Conclusion</h3><p>Jetpack Compose revolutionizes Android UI development with its declarative syntax, rich set of widgets, and seamless integration with Material Design. By embracing Compose, developers can create elegant, responsive, and maintainable user interfaces that delight users and elevate the overall app experience. With its powerful state management capabilities and intuitive tooling, Jetpack Compose empowers developers to unleash their creativity and build exceptional Android apps.</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=904f977e31fb" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/jetpack-compose-a-comprehensive-guide-to-ui-development-904f977e31fb">Jetpack Compose: A Comprehensive Guide to UI Development</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[Bluetooth Overview for Android Developers]]></title>
            <link>https://medium.com/@cpvasani48/bluetooth-overview-for-android-developers-b6ec93889a96?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6ec93889a96</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[bluetooth]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 17:55:11 GMT</pubDate>
            <atom:updated>2024-03-12T17:55:11.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*n8KLLh67FBb_r81dxTX-XA.png" /></figure><p>Bluetooth technology has revolutionized the way devices communicate wirelessly over short distances. In the realm of Android development, integrating Bluetooth functionality into applications opens up a plethora of possibilities, from connecting to nearby devices for file transfer to controlling IoT gadgets. In this article, we’ll delve into how to harness Bluetooth capabilities in Android programmatically, covering permissions, setup, and providing practical examples for sending and receiving files.</p><h3>Permissions:</h3><p>Before diving into Bluetooth operations, it’s crucial to request the necessary permissions in your AndroidManifest.xml file. These permissions grant your application access to Bluetooth-related features. Here’s what you need:</p><pre>&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH_ADMIN&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot;/&gt;</pre><p>The BLUETOOTH permission allows your app to connect with Bluetooth devices, while BLUETOOTH_ADMIN permission grants administrative privileges like turning Bluetooth on/off. Additionally, READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions are required for reading and writing files on the device&#39;s external storage.</p><h3>Setting Up Bluetooth:</h3><p>To interact with Bluetooth devices programmatically, you’ll typically need to follow these steps:</p><ol><li>Checking Bluetooth Support: Before proceeding, it’s wise to verify whether the device supports Bluetooth. You can do this using the BluetoothAdapter class.</li></ol><pre>BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) {     // Device doesn&#39;t support Bluetooth }</pre><ol><li>Enabling Bluetooth: If Bluetooth is disabled, you should prompt the user to enable it. You can achieve this using an intent.</li></ol><pre>if (!bluetoothAdapter.isEnabled()) {     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }</pre><ol><li>Discovering Devices: To discover nearby Bluetooth devices, you can start a discovery process. Remember to register for the appropriate broadcast intents to receive notifications about discovered devices.</li></ol><pre>bluetoothAdapter.startDiscovery();</pre><ol><li>Register a BroadcastReceiver to listen for discovered devices.</li></ol><pre>IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, filter);</pre><ol><li>Connecting to a Device: Once you’ve discovered the desired device, establish a connection using its MAC address.</li></ol><pre>BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect();</pre><h3>Sending and Receiving Files:</h3><p>Let’s enhance our Bluetooth application example to include file sending and receiving capabilities.</p><pre>// Method to send a file via Bluetooth<br>private void sendFile(BluetoothDevice device, Uri fileUri) {<br>    try {<br>        BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);<br>        socket.connect();<br>        OutputStream outputStream = socket.getOutputStream();<br>        InputStream inputStream = getContentResolver().openInputStream(fileUri);<br>byte[] buffer = new byte[1024];<br>        int bytesRead;<br>        while ((bytesRead = inputStream.read(buffer)) != -1) {<br>            outputStream.write(buffer, 0, bytesRead);<br>        }<br>        socket.close();<br>    } catch (IOException e) {<br>        e.printStackTrace();<br>    }<br>}<br>// Method to receive a file via Bluetooth<br>private void receiveFile(BluetoothSocket socket, File outputFile) {<br>    try {<br>        InputStream inputStream = socket.getInputStream();<br>        FileOutputStream outputStream = new FileOutputStream(outputFile);<br>        byte[] buffer = new byte[1024];<br>        int bytesRead;<br>        while ((bytesRead = inputStream.read(buffer)) != -1) {<br>            outputStream.write(buffer, 0, bytesRead);<br>        }<br>        outputStream.close();<br>        socket.close();<br>    } catch (IOException e) {<br>        e.printStackTrace();<br>    }<br>}<br>// Handle onActivityResult for file selection<br>@Override<br>protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {<br>    super.onActivityResult(requestCode, resultCode, data);<br>    if (requestCode == REQUEST_PICK_FILE &amp;&amp; resultCode == RESULT_OK) {<br>        Uri fileUri = data.getData();<br>        BluetoothDevice device = ... // Get the device to send the file to<br>        sendFile(device, fileUri);<br>    }<br>}</pre><p>In this enhanced example, we’ve added methods to send and receive files over Bluetooth connections. The sendFile() method sends a file to the specified Bluetooth device, while the receiveFile() method receives a file via Bluetooth and saves it to the device&#39;s storage. Additionally, we handle the file selection process using onActivityResult() to obtain the file URI and initiate the file transfer process.</p><h3>Conclusion:</h3><p>Integrating Bluetooth functionality into your Android applications expands their capabilities, enabling seamless communication and data transfer between devices. By following the steps outlined in this article and leveraging the provided examples, you can empower your apps with Bluetooth capabilities, opening doors to a wide range of innovative possibilities in the realm of wireless connectivity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6ec93889a96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Activity Lifecycle]]></title>
            <link>https://medium.com/@cpvasani48/android-activity-lifecycle-aebaa46caca1?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/aebaa46caca1</guid>
            <category><![CDATA[lifecycle]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 18:32:44 GMT</pubDate>
            <atom:updated>2024-02-05T18:32:44.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*MYcUJ0wLeh0SdmBxikP8jg.png" /><figcaption>Activity life cycle graph</figcaption></figure><h3>onCreate()</h3><p>You must implement this callback, which fires when the system first creates the activity. On activity creation, the activity enters the <em>Created</em> state. In the <a href="https://developer.android.com/reference/android/app/Activity#onCreate(android.os.Bundle)">onCreate()</a> method, perform basic application startup logic that happens only once for the entire life of the activity.</p><p>For example, your implementation of onCreate() might bind data to lists, associate the activity with a <a href="https://developer.android.com/reference/androidx/lifecycle/ViewModel">ViewModel</a>, and instantiate some class-scope variables. This method receives the parameter savedInstanceState, which is a <a href="https://developer.android.com/reference/android/os/Bundle">Bundle</a> object containing the activity&#39;s previously saved state. If the activity has never existed before, the value of the Bundle object is null.</p><p>If you have a lifecycle-aware component that is hooked up to the lifecycle of your activity, it receives the <a href="https://developer.android.com/reference/androidx/lifecycle/Lifecycle.Event#ON_CREATE">ON_CREATE</a> event. The method annotated with @OnLifecycleEvent is called so your lifecycle-aware component can perform any setup code it needs for the created state.</p><p>see the <a href="https://developer.android.com/guide/topics/ui">user interface</a> documentation.</p><p>Your activity does not remain in the Created state. After the onCreate() method finishes execution, the activity enters the <em>Started</em> state and the system calls the <a href="https://developer.android.com/reference/android/app/Activity#onStart()">onStart()</a> and <a href="https://developer.android.com/reference/android/app/Activity#onResume()">onResume()</a> methods in quick succession.</p><h3>onStart()</h3><p>When the activity enters the Started state, the system invokes <a href="https://developer.android.com/reference/android/app/Activity#onStart()">onStart()</a>. This call makes the activity visible to the user as the app prepares for the activity to enter the foreground and become interactive. For example, this method is where the code that maintains the UI is initialized.</p><p>When the activity moves to the Started state, any lifecycle-aware component tied to the activity’s lifecycle receives the <a href="https://developer.android.com/reference/androidx/lifecycle/Lifecycle.Event#ON_START">ON_START</a> event.</p><p>The onStart() method completes quickly and, as with the Created state, the activity does not remain in the Started state. Once this callback finishes, the activity enters the <em>Resumed</em> state and the system invokes the <a href="https://developer.android.com/reference/android/app/Activity#onResume()">onResume()</a> method.</p><h3>onResume()</h3><p>When the activity enters the Resumed state, it comes to the foreground, and the system invokes the <a href="https://developer.android.com/reference/android/app/Activity#onResume()">onResume()</a> callback. This is the state in which the app interacts with the user. The app stays in this state until something happens to take focus away from the app, such as the device receiving a phone call, the user navigating to another activity, or the device screen turning off.</p><p>When the activity moves to the Resumed state, any lifecycle-aware component tied to the activity’s lifecycle receives the <a href="https://developer.android.com/reference/androidx/lifecycle/Lifecycle.Event#ON_RESUME">ON_RESUME</a> event. This is where the lifecycle components can enable any functionality that needs to run while the component is visible and in the foreground, such as starting a camera preview.</p><p>When an interruptive event occurs, the activity enters the <em>Paused</em> state and the system invokes the <a href="https://developer.android.com/reference/android/app/Activity#onPause()">onPause()</a> callback.</p><p>If the activity returns to the Resumed state from the Paused state, the system once again calls the onResume() method. For this reason, implement onResume() to initialize components that you release during onPause() and to perform any other initializations that must occur each time the activity enters the Resumed state.</p><p><a href="https://developer.android.com/topic/libraries/architecture/lifecycle">cycles with Lifecycle-Aware Components</a>.</p><h3>onPause()</h3><p>The system calls this method as the first indication that the user is leaving your activity, though it does not always mean the activity is being destroyed. It indicates that the activity is no longer in the foreground, but it is still visible if the user is in multi-window mode. There are several reasons why an activity might enter this state:</p><ul><li>An event that interrupts app execution, as described in the section about the <a href="https://developer.android.com/guide/components/activities/activity-lifecycle#onresume">onResume()</a> callback, pauses the current activity. This is the most common case.</li><li>In multi-window mode, only one app has focus at any time, and the system pauses all the other apps.</li><li>The opening of a new, semi-transparent activity, such as a dialog, pauses the activity it covers. As long as the activity is partially visible but not in focus, it remains paused.</li></ul><p>When an activity moves to the Paused state, any lifecycle-aware component tied to the activity’s lifecycle receives the <a href="https://developer.android.com/reference/androidx/lifecycle/Lifecycle.Event#ON_PAUSE">ON_PAUSE</a> event. This is where the lifecycle components can stop any functionality that does not need to run while the component is not in the foreground, such as stopping a camera preview.</p><p>Use the <a href="https://developer.android.com/reference/android/app/Activity#onPause()">onPause()</a> method to pause or adjust operations that can&#39;t continue, or might continue in moderation, while the Activity is in the Paused state, and that you expect to resume shortly.</p><p>You can also use the onPause() method to release system resources, handles to sensors (like GPS), or any resources that affect battery life while your activity is Paused and the user does not need them.</p><p>However, as mentioned in the section about onResume(), a Paused activity might still be fully visible if the app is in multi-window mode. Consider using onStop() instead of onPause() to fully release or adjust UI-related resources and operations to better support multi-window mode.</p><h3>onStop()</h3><p>When your activity is no longer visible to the user, it enters the <em>Stopped</em> state, and the system invokes the <a href="https://developer.android.com/reference/android/app/Activity#onStop()">onStop()</a> callback. This can occur when a newly launched activity covers the entire screen. The system also calls onStop() when the activity finishes running and is about to be terminated.</p><p>When the activity moves to the Stopped state, any lifecycle-aware component tied to the activity’s lifecycle receives the <a href="https://developer.android.com/reference/androidx/lifecycle/Lifecycle.Event#ON_STOP">ON_STOP</a> event. This is where the lifecycle components can stop any functionality that does not need to run while the component is not visible on the screen.</p><p>In the onStop() method, release or adjust resources that are not needed while the app is not visible to the user. For example, your app might pause animations or switch from fine-grained to coarse-grained location updates. Using onStop() instead of <a href="https://developer.android.com/reference/android/app/Activity#onPause()">onPause()</a> means that UI-related work continues, even when the user is viewing your activity in multi-window mode.</p><p>Also, use onStop() to perform relatively CPU-intensive shutdown operations. For example, if you can&#39;t find a better time to save information to a database, you might do so during onStop().</p><h3>onDestroy()</h3><p><a href="https://developer.android.com/reference/android/app/Activity#onDestroy()">onDestroy()</a> is called before the activity is destroyed. The system invokes this callback for one of two reasons:</p><ol><li>The activity is finishing, due to the user completely dismissing the activity or due to <a href="https://developer.android.com/reference/android/app/Activity#finish()">finish()</a> being called on the activity.</li><li>The system is temporarily destroying the activity due to a configuration change, such as device rotation or entering multi-window mode.</li></ol><p>When the activity moves to the destroyed state, any lifecycle-aware component tied to the activity’s lifecycle receives the <a href="https://developer.android.com/reference/androidx/lifecycle/Lifecycle.Event#ON_DESTROY">ON_DESTROY</a> event. This is where the lifecycle components can clean up anything they need to before the Activity is destroyed.</p><p>Instead of putting logic in your Activity to determine why it is being destroyed, use a <a href="https://developer.android.com/reference/androidx/lifecycle/ViewModel">ViewModel</a> object to contain the relevant view data for your Activity. If the Activity is recreated due to a configuration change, the ViewModel does not have to do anything, since it is preserved and given to the next Activity instance.</p><p>If the Activity isn&#39;t recreated, then the ViewModel has the <a href="https://developer.android.com/reference/androidx/lifecycle/ViewModel#onCleared()">onCleared()</a> method called, where it can clean up any data it needs to before being destroyed. You can distinguish between these two scenarios with the <a href="https://developer.android.com/reference/android/app/Activity#isFinishing()">isFinishing()</a> method.</p><p>If the activity is finishing, onDestroy() is the final lifecycle callback the activity receives. If onDestroy() is called as the result of a configuration change, the system immediately creates a new activity instance and then calls <a href="https://developer.android.com/reference/android/app/Activity#onCreate(android.os.Bundle)">onCreate()</a> on that new instance in the new configuration.</p><p>The onDestroy() callback releases all resources not released by earlier callbacks, such as <a href="https://developer.android.com/reference/android/app/Activity#onStop()">onStop()</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aebaa46caca1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Simple 2D Game in Android Using Kotlin and Coroutines]]></title>
            <link>https://medium.com/@cpvasani48/creating-a-simple-2d-game-in-android-using-kotlin-and-coroutines-74976480e5a3?source=rss-326679117500------2</link>
            <guid isPermaLink="false">https://medium.com/p/74976480e5a3</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Chirag Vasani]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 18:50:21 GMT</pubDate>
            <atom:updated>2024-01-30T18:50:21.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*d7FDM3o1slPzUN8Dd_lAmg.gif" /></figure><p>In this tutorial, we’ll create a basic 2D game for Android using Kotlin and coroutines. Our game will feature a bouncing ball that moves around the screen. This example will help you understand the fundamentals of game development on the Android platform.</p><h3>Setting Up the Project</h3><ol><li>Open Android Studio and create a new Android project with an Empty Activity.</li><li>Set the language to Kotlin.</li></ol><h3>Creating the GameView</h3><p>We’ll start by creating a custom SurfaceView to handle the game rendering. This class will be responsible for drawing the ball and updating its position.</p><pre>// GameView.kt<br><br>import android.content.Context<br>import android.graphics.Canvas<br>import android.graphics.Color<br>import android.graphics.Paint<br>import android.view.SurfaceHolder<br>import android.view.SurfaceView<br>import kotlinx.coroutines.CoroutineScope<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.launch<br>import kotlin.random.Random<br><br>class GameView(context: Context) : SurfaceView(context), SurfaceHolder.Callback {<br><br>    private var thread: GameThread? = null<br>    private var ballX: Float = 100f<br>    private var ballY: Float = 100f<br>    private var ballRadius: Float = 30f<br>    private var speedX: Float = 5f<br>    private var speedY: Float = 5f<br><br>    init {<br>        holder.addCallback(this)<br>    }<br><br>    override fun surfaceCreated(holder: SurfaceHolder) {<br>        thread = GameThread(holder, this)<br>        thread?.start()<br>    }<br><br>    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}<br><br>    override fun surfaceDestroyed(holder: SurfaceHolder) {<br>        var retry = true<br>        while (retry) {<br>            try {<br>                thread?.join()<br>                retry = false<br>            } catch (e: InterruptedException) {<br>                // Retry<br>            }<br>        }<br>    }<br><br>    fun resumeGame() {<br>        thread?.running = true<br>    }<br><br>    fun pauseGame() {<br>        thread?.running = false<br>    }<br><br>    fun update() {<br>        ballX += speedX<br>        ballY += speedY<br><br>        // Bounce the ball when it hits the screen edges<br>        if (ballX - ballRadius &lt; 0 || ballX + ballRadius &gt; width) {<br>            speedX = -speedX<br>        }<br><br>        if (ballY - ballRadius &lt; 0 || ballY + ballRadius &gt; height) {<br>            speedY = -speedY<br>        }<br>    }<br><br>    override fun draw(canvas: Canvas) {<br>        super.draw(canvas)<br>        canvas.drawColor(Color.BLACK)<br>        val paint = Paint()<br>        paint.color = Color.WHITE<br>        canvas.drawCircle(ballX, ballY, ballRadius, paint)<br>    }<br>}</pre><h3>Creating the GameThread</h3><p>Next, we’ll create a separate thread to handle the game loop. This thread will continuously update the game state and redraw the screen.</p><pre>// GameThread.kt<br><br>import android.graphics.Canvas<br>import android.view.SurfaceHolder<br><br>class GameThread(private val surfaceHolder: SurfaceHolder, private val gameView: GameView) : Thread() {<br><br>    var running = false<br><br>    override fun run() {<br>        while (running) {<br>            val canvas: Canvas? = surfaceHolder.lockCanvas()<br>            if (canvas != null) {<br>                gameView.update()<br>                gameView.draw(canvas)<br>                surfaceHolder.unlockCanvasAndPost(canvas)<br>            }<br><br>            try {<br>                sleep(16) // Adjust frame rate as needed<br>            } catch (e: InterruptedException) {<br>                e.printStackTrace()<br>            }<br>        }<br>    }<br>}</pre><h3>Integrating the GameView into MainActivity</h3><p>Finally, we’ll integrate our GameView into the MainActivity.</p><pre>// MainActivity.kt<br><br>import android.os.Bundle<br>import androidx.appcompat.app.AppCompatActivity<br><br>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var gameView: GameView<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        gameView = GameView(this)<br>        setContentView(gameView)<br>    }<br><br>    override fun onResume() {<br>        super.onResume()<br>        gameView.resumeGame()<br>    }<br><br>    override fun onPause() {<br>        super.onPause()<br>        gameView.pauseGame()<br>    }<br>}</pre><h3>Conclusion</h3><p>In this tutorial, we’ve created a simple 2D game for Android using Kotlin and coroutines. This example introduces you to the basic concepts of game development on the Android platform. Feel free to expand on this example by adding more features, improving graphics, or implementing additional game mechanics. Happy coding!</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p>Certainly! The above example is a simple demonstration of a bouncing ball game. Here are the key features of the game:</p><ol><li>Bouncing Ball: The game features a ball that moves around the screen.</li><li>Screen Bouncing: When the ball reaches the edges of the screen, it “bounces” back in the opposite direction. This gives the illusion of the ball bouncing off the screen boundaries.</li><li>Custom SurfaceView: The game rendering is handled by a custom SurfaceView called GameView. This view is responsible for drawing the ball on the canvas.</li><li>Game Loop: The game loop is implemented in a separate thread (GameThread). This loop continuously updates the game state (e.g., ball position) and redraws the screen.</li><li>Coroutines: While coroutines are imported and used in the GameView class, they are not explicitly utilized in this simple example. Coroutines could be used for handling more complex asynchronous tasks in a larger game.</li></ol><p>The main components are the GameView, GameThread, and MainActivity. The GameView handles the drawing of the ball and contains the game logic, while the GameThread manages the game loop. The MainActivity sets up and manages the GameView.</p><p>This is a very basic example meant for educational purposes. In a real-world scenario, you would expand on this foundation by adding more features, such as user input for controlling the ball, multiple bouncing objects, scoring mechanisms, and possibly more complex game physics.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Android Demos : <a href="https://github.com/ChiragVasaniP">Click here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74976480e5a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>