<?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 Krithika Ravishankar on Medium]]></title>
        <description><![CDATA[Stories by Krithika Ravishankar on Medium]]></description>
        <link>https://medium.com/@kritstudy15?source=rss-dba10a3097e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3XgUdQCXc7jIvI5oY6q7Ig.jpeg</url>
            <title>Stories by Krithika Ravishankar on Medium</title>
            <link>https://medium.com/@kritstudy15?source=rss-dba10a3097e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:12:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kritstudy15/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[Building ReflectAI: An AI-Powered Mindfulness Companion for Android]]></title>
            <link>https://medium.com/@kritstudy15/building-reflectai-an-ai-powered-mindfulness-companion-for-android-2f628c2b3f2f?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f628c2b3f2f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[hack2skill]]></category>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 18:00:11 GMT</pubDate>
            <atom:updated>2026-09-06T18:00:11.896Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I combined Gemini’s multi-turn conversations, Firebase’s real-time sync, and a little bit of Zen design philosophy to build a journaling app that actually listens.</em></p><p>#AccelerateAIwithCloudRun</p><p>Most journaling apps are glorified text boxes. You type, you save, and the app forgets you exist until tomorrow. I wanted to build something different — an app that could hold a conversation, remember the thread of your thoughts across a session, and respond with the kind of presence you’d expect from an actual companion, not a form field.</p><p>That’s the idea behind <strong>ReflectAI</strong>: a reflection journaling and mindfulness app for Android, built with Kotlin, Jetpack Compose, and Google’s Gemini API, wrapped in a calm, twilight-and-sage aesthetic designed to make sitting down with your thoughts feel less like a chore and more like a ritual.</p><p>Here’s how it came together.</p><h3>The Problem With Static Journaling</h3><p>Early prototypes of the app used one-shot prompts — you’d write an entry, send it to the model, get a reflection back, and that was the end of the exchange. It worked, but it felt hollow. Real reflection isn’t a single question-and-answer; it’s a back-and-forth. You say something, get a nudge, and then you go deeper.</p><p>So the core architectural decision was to move from single-shot completions to genuine <strong>multi-turn dialogue</strong>. Every conversation now tracks its own history through a ConversationTurn model, which gets passed along with each new message so the model has full context of what&#39;s already been said. On the frontend, this shows up as a MultiTurnConversationCard — a proper chat thread with user and AI message bubbles, a follow-up input bar, and the option to reset the thread when you want a clean slate.</p><p>To keep things resilient, requests route primarily through gemini-2.5-flash, with automatic fallbacks to gemini-3.1-flash-lite and gemini-2.5-pro if the primary call fails. The app also supports a small cast of companion personas — Maya for emotional processing, Marcus for stoic decision-making, Elena for creative brainstorming, and David for grounding mindfulness — so the tone of the conversation can shift depending on what you actually need that day.</p><h3>Getting the Privacy Model Right</h3><p>An app that stores people’s private reflections has exactly one job to get right before anything else: making sure nobody’s data leaks into anybody else’s space.</p><p>ReflectAI handles this through <strong>Firebase Authentication</strong> paired with strictly isolated Firestore paths — every interaction lives under /users/{userId}/interactions/{interactionId}, so there&#39;s no ambiguity about ownership at the database level. Users can sign in with email and password, jump in anonymously as a guest, or use an isolated sandbox session for local testing.</p><p>On top of that, the app is offline-first. A local Room database caches everything immediately, and a real-time Firestore listener syncs it to the cloud in the background. So if your connection drops mid-reflection, nothing is lost — it’s already sitting safely on-device, waiting to sync.</p><h3>Secrets Don’t Belong in Your Codebase</h3><p>API keys hardcoded into an app are a liability waiting to happen. ReflectAI pulls its Gemini API key at runtime through a CloudSecretManagerService, which talks directly to the Google Cloud Secret Manager REST API. Keys are cached in memory only — never written to disk, never logged, and cleared the moment a user logs out. If Secret Manager isn&#39;t available (say, during local development), the app falls back gracefully to a BuildConfig value injected through the Secrets Gradle Plugin.</p><p>It’s a small detail, but it’s the difference between a demo project and something you’d actually trust with real data.</p><h3>Designing for Calm</h3><p>None of the engineering matters if opening the app feels stressful. So the UI leans into a deliberately soft palette — twilight blues, sage greens, lavender, and warm amber — built on Material Design 3.</p><p>The centerpiece is a <strong>mindful breathing widget</strong>: an animated circle that guides you through a 4–4–4 breathing pattern (inhale, hold, exhale, rest), paired with rotating daily affirmations. There’s also a set of companion avatars that visually shift between listening, resting, and generating-insight states, so the AI feels present rather than transactional — a small animation cue that says <em>I’m still here</em> while a response is being generated.</p><p>Beyond the chat itself, the app supports multimodal input — text, voice notes with live amplitude visualization, and photo attachments — plus a searchable history view with category filters for tracks like Gratitude, Stress Relief, Self-Discovery, and Focus &amp; Career.</p><h3>The Stack, Briefly</h3><ul><li><strong>Architecture:</strong> MVVM with Clean Architecture principles</li><li><strong>UI:</strong> Jetpack Compose + Material 3</li><li><strong>Language:</strong> Kotlin 2.0+, Coroutines &amp; StateFlow</li><li><strong>AI:</strong> Gemini API (2.5-flash → 3.1-flash-lite → 2.5-pro fallback ladder)</li><li><strong>Backend:</strong> Firebase Auth + Cloud Firestore</li><li><strong>Local storage:</strong> Room (with KSP)</li><li><strong>Networking:</strong> OkHttp 4 + Moshi</li><li><strong>Secrets:</strong> Google Cloud Secret Manager + Secrets Gradle Plugin</li><li><strong>Testing:</strong> Robolectric + Roborazzi for screenshot regression</li></ul><h3>What I Learned</h3><p>Building ReflectAI reinforced something I keep relearning on every project: the “invisible” infrastructure — auth isolation, offline sync, secret management — takes as much design thinking as the visible UI. A breathing widget is delightful, but it means nothing if a user’s private reflections aren’t actually private, or if the app falls apart the moment Wi-Fi drops.</p><p>The next steps are sharpening the persona system further and experimenting with longer-term memory across sessions — so ReflectAI doesn’t just hold context within one conversation, but starts to genuinely understand the arc of someone’s reflective practice over weeks, not minutes.</p><p><em>ReflectAI is a work in progress, built as an exploration of what AI-assisted mindfulness tools can look like when privacy, resilience, and calm design are treated as first-class requirements rather than afterthoughts.</em></p><p>github link: <a href="https://github.com/Kritzr/ReflectAI_Journal">https://github.com/Kritzr/ReflectAI_Journal</a><br>demo link: <a href="https://drive.google.com/drive/folders/1RttGHdQsnBfoLizAqUkiIDCZ-8OwhFC1?usp=drive_link">https://drive.google.com/drive/folders/1RttGHdQsnBfoLizAqUkiIDCZ-8OwhFC1?usp=drive_link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f628c2b3f2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking the sound barrier: Building a Two way Indian Sign Language Translator with Google AI]]></title>
            <link>https://medium.com/@kritstudy15/breaking-the-sound-barrier-building-a-two-way-indian-sign-language-translator-with-google-ai-8ade62387c00?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ade62387c00</guid>
            <category><![CDATA[google-ai]]></category>
            <category><![CDATA[meet-the-builders]]></category>
            <category><![CDATA[isls]]></category>
            <category><![CDATA[buildwithpurpose]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 05:37:36 GMT</pubDate>
            <atom:updated>2026-08-31T05:37:36.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*FoxUsqDIlHffkNkUyTjmag.jpeg" /></figure><p>Growing up, I spent a lot of time volunteering at orphanages and old age homes, performing classical dance to help raise funds. Whenever I met Deaf children and elders there, people often assumed I could easily talk to them because of my dance training.</p><p>I tried. I would use my <em>mudras</em> (hand gestures) to bridge the gap, but classical dance hand gestures are not a language. While a few basic emotions came through, I hit an immediate wall.</p><p>They had vibrant imaginations, incredible stories, and innovative ideas to share -and I desperately wanted to listen, converse, and truly understand their thoughts. But our languages were entirely different. That lingering feeling of being in the same room with brilliant minds yet separated by an invisible linguistic wall stayed with me.</p><p>Over 60 million people in India live with significant hearing loss or deafness, and Indian Sign Language (ISL) is their primary, natural mother tongue. Yet, fewer than a few hundred certified ISL interpreters exist across the entire country.</p><p>Most people assume sign language is just finger-spelling words letter-by-letter. It isn’t. ISL is an independent, complete visual language with its own grammar, spatial syntax, and rich non-manual markers (like eyebrow movements and head tilts). Standard machine translation fails because you cannot translate spoken regional languages into ISL through word-by-word substitution.</p><p>As a student passionate about technology and accessibility, I wanted to turn that childhood realization into a working reality: a genuine, two-way bridge that translates spoken and written regional languages into ISL syntax and back in real time.</p><p>That led me to build Chandesh<strong>AI (சண்டேசுவர</strong>/चंदेश्वर<strong>)</strong></p><p>Being part of Cohort 3 of the Google Cloud Gen AI Academy (APAC Edition) provided the hands-on foundation and Google AI tooling I needed to bring ChandeshAI to life.</p><p><strong>ChandeshAI</strong> is a bidirectional Indian Sign Language translation bridge designed to run smoothly on standard smartphones and web browsers.</p><p>The application operates in two clear directions:</p><ol><li><strong>Hearing →Deaf:</strong> Converts natural vernacular speech into structured <strong>ISL Gloss</strong> (the grammatical notation of sign language) and renders it through a synchronized visual sequence.</li><li><strong>Deaf →Hearing:</strong> Extracts 3D hand and pose landmarks from camera feeds in real time, converts sign sequences into context-aware sentences, and speaks them out loud in regional languages.</li></ol><p>Mode 1: Voice/Text ➔ ISL — — Spoken Hindi/Tamil/English ➔ Gemini Structured Gloss Parser ➔ Synchronized Sign Video/Avatar</p><p>Mode 2: ISL Video ➔ Voice/Text] Camera Feed (Live Gesture) ➔ MediaPipe Holistic Landmarks ➔ Gemini Multimodal ➔ Fluent Speech</p><h3>How It Works</h3><pre>CHANDESHAI ARCHITECTURE PIPELINE<br>                        <br>    ┌──────────────────────────┐          ┌──────────────────────────┐<br>    │  Audio / Vernacular Text │          │   Live ISL Camera Feed   │<br>    └─────────────┬────────────┘          └─────────────┬────────────┘<br>                  │                                     │<br>                  ▼                                     ▼<br>    ┌──────────────────────────┐          ┌──────────────────────────┐<br>    │ Google Speech-to-Text    │          │ Google MediaPipe Holistic│<br>    │  (Regional Languages)    │          │   (Hands, Pose &amp; Face)   │<br>    └─────────────┬────────────┘          └─────────────┬────────────┘<br>                  │                                     │<br>                  ▼                                     ▼<br>    ┌──────────────────────────┐          ┌──────────────────────────┐<br>    │ Gemini 1.5 / 2.0 Flash   │          │ Gemini Multimodal &amp;      │<br>    │ (ISL Grammar Restructure)│          │ Temporal Gloss Parser    │<br>    └─────────────┬────────────┘          └─────────────┬────────────┘<br>                  │                                     │<br>                  ▼                                     ▼<br>    ┌──────────────────────────┐          ┌──────────────────────────┐<br>    │ Visual Dictionary &amp;      │          │ Google Text-to-Speech    │<br>    │ Keyframe Animation Engine│          │  (Natural Spoken Audio)  │<br>    └──────────────────────────┘          └──────────────────────────┘</pre><h4>1. Linguistic Restructuring (Natural Speech $\rightarrow$ ISL Gloss)</h4><p>When someone says: <em>“I will not be able to attend the meeting tomorrow because of rain.”</em></p><p>The system feeds this to <strong>Gemini Flash</strong>, using structured schema outputs to reorganize the syntax into ISL Subject-Object-Verb / Topic-Comment order:</p><p>Input: Spoken English →ISL Gloss: [TOMORROW, RAIN, MEETING, ATTEND, CANNOT]</p><h4>2. Real-Time Vision Tracking (ISL $\rightarrow$ Spoken Language)</h4><p>Rather than streaming heavy video frames to the cloud, the app runs <strong>Google MediaPipe Holistic</strong> client-side on device. It captures:</p><ul><li><strong>21 3D points</strong> per hand (42 landmarks)</li><li><strong>33 pose coordinates</strong> for torso and shoulder angles</li><li><strong>Face Mesh points</strong> to register non-manual expressions (like head shakes for negation)</li></ul><p>These lightweight vector streams are classified into gloss sequences and fed into Gemini to generate full, grammatically polished sentences in the chosen regional language.</p><h3>Technology Behind the Project</h3><ul><li><strong>Google Cloud &amp; Vertex AI / Google AI Studio:</strong> Prompting and deploying <strong>Gemini 1.5/2.0 Flash</strong> for bidirectional grammatical gloss extraction and translation.</li><li><strong>Google MediaPipe:</strong> On-device, client-side vision pipeline for 3D hand and pose tracking without network latency bottlenecks.</li><li><strong>Google Cloud Speech-to-Text &amp; Text-to-Speech:</strong> Handling vernacular voice input and natural audio playback.</li><li><strong>Frontend Client:</strong> Built with modern web/mobile frameworks, running local landmark inference seamlessly.</li><li><strong>Firebase (Firestore &amp; Storage):</strong> Managing the sign-gesture video library, indexed dictionaries, and user interaction logs.</li></ul><h3>Challenges I Faced</h3><ul><li><strong>Sign Language is Not Transliteration:</strong> My initial prototypes produced naive, word-by-word fingerspelling, which felt robotic and unnatural to native signers. I had to fine-tune Gemini prompts with explicit ISL grammatical rules — stripping out auxiliary verbs, front-loading time markers, and handling question words at sentence ends.</li><li><strong>Bandwidth Constraints:</strong> Sending uncompressed video streams over mobile data caused noticeable lag. Shifting landmark extraction to the client using <strong>MediaPipe</strong> reduced payload size by over <strong>90%</strong>, keeping the experience fast and responsive.</li><li><strong>Dialect and Gesture Nuance:</strong> Just like spoken languages, sign gestures vary across different regions. Building an open dictionary format allowed the system to accommodate regional variations over time.</li></ul><h3>What I Learned</h3><p>Building <strong>chandeshAI</strong> taught me that inclusive technology requires understanding lived human experience first, and choosing algorithms second.</p><p>Machine learning is not just about raw model benchmarks or theoretical scores -it is about creating intuitive digital bridges that give real people agency, dignity, and independence in everyday social interactions.</p><h3>What’s Next?</h3><ul><li><strong>3D Rigged WebGL Avatar:</strong> Upgrading the visual playback pipeline from pre-recorded dictionary clips to a dynamic, real-time 3D avatar capable of continuous fluid motion.</li><li><strong>Offline On-Device Inference:</strong> Porting the core language translation logic to run directly on-device using lightweight models like <strong>Gemma 2B</strong> via MediaPipe GenAI.</li><li><strong>Classroom &amp; Public Desk Mode:</strong> Packaging the tool for smart display setups in government offices, university help desks, and emergency hospital triage counters.</li></ul><h3>My Builder Journey</h3><p>I started this journey remembering the times I stood in front of expressive children, wishing my dance mudras could turn into real conversations.</p><p>I joined the <strong>Meet the Builders</strong> initiative with a single goal:</p><blockquote>Can we make communication truly accessible for every voice, spoken or silent?</blockquote><p><strong>chandeshAI</strong> is my attempt to build that bridge. True innovation happens when advanced AI leaves research papers behind and helps two people understand each other across a table. A huge thank you to the Google Cloud Gen AI Academy (APAC Edition, Cohort 3). The hands-on learning from this cohort gave me the exact tools and confidence to build a solution for such a meaningful cause.</p><p>This is only step one.</p><p><strong>Tags:</strong> Google AI · Meet The Builders · Indian Sign Language · Accessibility · Gemini API · MediaPipe · BuildWithAPurpose</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ade62387c00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Pixel — I just love it, and here's why it is better for Android coders]]></title>
            <link>https://medium.com/@kritstudy15/google-pixel-i-just-love-it-and-heres-why-it-is-better-for-android-coders-d1b9d2bcc42c?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1b9d2bcc42c</guid>
            <category><![CDATA[google-pixel]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 09:17:03 GMT</pubDate>
            <atom:updated>2026-06-11T09:17:03.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKa6n_Id_d47zaqQvBJmNQ.png" /><figcaption>Summary Image</figcaption></figure><p>I have been using Google Pixel 7A for the past 2 years, and honestly, it was one of the best decisions I took. I am not going to be backing up by saying that it is an ideal phone, but there are some features that I genuinely liked, and why I feel that it is more suitable for Android coders.</p><p>Pixel runs a reference version of Android directly from Google, it exposes the OS Architecture beautifully without any heavy manufacturer skins.</p><p>In order to unlock this matrix of diagnostic and profiling features built into Android, you need to turn on your developer settings.</p><ul><li>Go to <strong>Settings &gt; About phone</strong>.</li><li>Scroll all the way to the bottom and tap <strong>Build number</strong> 7 times.</li><li>You’ll see a notification saying <em>“You are now a developer!”</em> Now, go back to <strong>Settings &gt; System</strong>, and you will see a new menu called <strong>Developer options</strong>. Inside here, you can turn on visual overlays that show the OS working in real-time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*LHIh2V8qqvDKDd5huBvfVQ.jpeg" /><figcaption>Enable developer options</figcaption></figure><p>Once this is set, you are to use it as an engineer. We focus now on debugging where i used most actually.</p><h3>The Debug features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msg5kOqN4vvoupISi-Bnlg.jpeg" /></figure><h4>USB Debugging</h4><p>While developing an android app, we connect our android devices to the android studio (or you could use a virtual device via the emulator). I used the former method, and this basically allows our computer to communicate with our android device using ADB (Android Debug Bridge). This helps in installing the said app via a command line, capture logs, run automation scripts and rooting or flashing devices.</p><p>This is done via a USB cable. But what if you didn’ have one?</p><h4>2. Wireless debugging</h4><p>this provides the adb access via wifi instead of USB cable. thi shas the same functionality as above but the downsides that i experienced were slight battery usage and it could be risk if connect to untrusted networks. I had to work in a secure network and so, i didn’t need to worry about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86MWQ67YdhhDZxPEaRSvlQ.jpeg" /></figure><h4>3. Revoke USB Debugging Authorizations</h4><p>When you want to forget your previously trusted computer like you wish you did your ex, this is it.</p><h4>4. Disable ADB Authorisation Timeout</h4><p>Android usually forgets inactive ADB authorisations after a period of time. So this disables. It is useful for the case when you don’t really switch out your testing device.</p><h4>5. Linux Development Environment (experimental)</h4><p>This is one of the newest feture and it had very interesting features. It allows running a linux environmnet directly on android. This opens up new avenues for python/ML development, git operations, linux command line convinence and containerised development. This is particularly exciting for me because i see android moving toward to becoming a lightweight development platform.</p><h4>6. Bug report shortcut</h4><p>This adds a bug report button to the power menu. This collects the system logs, crash reports, hardware info and running processes displayed. real helpful when you are searching for bugs.</p><h4>7. Enable verbose vendor logging</h4><p>Now this was different because i really couldn’t particularly use it. It basically helps us collect additional logs from device manufactureres. For example from your model, or camera subsystem etc., If you have tried it out, let me know. the cons are that it would consume more storage and battery and would be containing sensitive info.</p><p>Now if it is specific to printing devices, you use Verbose Print Logging.</p><h4>8. Enable View Attribute Inspection :</h4><p>Now this is one of my favorites. This allows the inspection of UI Elements and their properties. So this helps the developer to see the view hierarchy, the layout parameters, the padding and the margins, and the accessibility properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaUPuFwq9anJtJfVHqmlSA.jpeg" /></figure><h4>9. Select debug app and wait for debugger:</h4><p>forces android to attach a debugger to a specific app and wait for debugger basically tells the app to wait till the debugger is attached.</p><h4>10. System Tracing</h4><p>One of Android’s most powerful performance tools. It records detailed timing information about CPU activity, Threads, Rendering, App launches and I/O operations. It is used for Performance optimization, Finding bottlenecks, Frame drop analysis.</p><p>If you’ve ever wondered how Android engineers diagnose lag, this is one of their key tools.</p><h3>Why this matters on a Pixel specifically</h3><p>All of these settings exist on any Android device with Developer Options enabled. So why does the Pixel make them more useful?</p><p>Because on a manufacturer-skinned device, you’re debugging two things at once: your app, and whatever the OEM has done to the OS. Samsung’s One UI, Xiaomi’s MIUI, and others introduce their own memory management layers, background task killers, and UI rendering modifications on top of Android. The baseline isn’t clean.</p><p>On a Pixel, what you see in Developer Options is exactly what the Android documentation describes. There’s no intermediary. When you toggle App Compatibility Changes, you’re interacting with AOSP (Android Open Source Project) directly, the same OS your app will run on in the Android Emulator, in Firebase Test Lab, and on the reference implementations that Google uses to validate platform behaviour. The diagnostic tools work as documented because the OS is exactly what the documentation assumes.</p><p>For an Android developer, that’s not a small thing. That’s the entire difference between debugging a problem and debugging a rumour.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1b9d2bcc42c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Architecture Design Patterns: MVC, MVP, MVVM, MVI]]></title>
            <link>https://medium.com/@kritstudy15/android-architecture-design-patterns-mvc-mvp-mvvm-mvi-1b5757c8fbfe?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b5757c8fbfe</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Wed, 06 May 2026 11:34:48 GMT</pubDate>
            <atom:updated>2026-05-06T11:34:48.556Z</atom:updated>
            <content:encoded><![CDATA[<p>When you are trying to build an Android app, your manager or your supervisor is going to ask you to prevent spaghetti code (the one where your business logic is tangled with your UI) and make it difficult to maintain, scale, and test the app. You will know where the UI Logic is and which API calls are. This works fine for a demo, but when you are working in a team, it becomes necessary to understand the importance of separating features for testability, debugging, and easier collaboration.</p><p>Based on my previous articles, we can understand that Android recommends a layered architecture in which we will have the data layer, which handles your Business Logic, the UI Layer, which handles the user interaction using compose, and the domain layer for the reusability of UI components for your business logic.</p><p>This architecture helps the developers face complexity. Especially as apps grow in size and features, these architectural patterns help maintain readability, testability, and scalability.</p><p>Let us focus on the 4 main archetypes.</p><p>Assume a fictional story in which there are these 4 characters through which you can understand the concepts more easily.</p><p>We will walk through MVC, MVP, MVVM, and MVI.</p><p>Visit this website I made for visual understanding: <a href="https://kritzr.github.io/androidarchi-demo/">https://kritzr.github.io/androidarchi-demo/</a></p><h3>EXPERIMENT</h3><p>I built a simple counter app. It has a state (count), has a user actions (increment, decrement, reset) and it is small enough to focus on the architecture.</p><h4>Shared Model:</h4><pre>// FILE: app/src/main/java/com/example/archidemo1/shared/CounterModel.kt<br><br>package com.example.archidemo1.shared<br><br>data class CounterModel(val count: Int = 0) {<br>    fun increment() = copy(count = count + 1)<br>    fun decrement() = copy(count = count - 1)<br>    fun reset()     = copy(count = 0)<br>}</pre><h3>MVC — Model View Controller — “I do everything myself “</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*limEK_sJZwvEQTsRFIeBvw.png" /></figure><p>The typical project teammate would end up doing the entire project all on their own. There is no delegation, no separation. The composable itself acts as a controller. It reads the model, mutates it, and updates the UI.</p><pre>var model by remember { mutableStateOf(CounterModel()) } Text(text = model.count.toString()) Button(onClick = { model = model.increment() })</pre><p>The jetpack compose itself supports this, but the composable ends up doing the state management, business logic, and UI rendering. When this small app is later to be developed for production (humour me), the API calls, navigation, and validation would explode almost immediately.</p><h4>PROS:</h4><p>&gt; fast to build</p><p>&gt; minimal setup</p><h4>CONS:</h4><p>&gt; no separation of concerns</p><p>&gt; hard to test</p><p>&gt; doesn’t scale</p><p>This is a one-way path to spaghetti code — clean at first, but chaotic later. The project immediately becomes something cooked up, but not as great as what it could be if it were built as a team.</p><h3>MVP — Model View Presenter — “Let me ask my mom.”</h3><p>This is that friend of ours who would want to recheck with their mother. Here, the view handles the UI, the presenter handles the logic, and the communication is made via an interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*MrUgzqdS0nzYBxOuPqwzfg.png" /></figure><pre>interface ICounterView {<br>    fun showCount(count: Int)<br>}<br>class CounterPresenter(private var view: ICounterView?) {<br><br>    private var model = CounterModel()<br><br>    fun onIncrement() {<br>        model = model.increment()<br>        view?.showCount(model.count)<br>    }<br>}<br>In Compose<br><br>The composable implements the interface:<br><br>val view = remember {<br>    object : ICounterView {<br>        override fun showCount(count: Int) {<br>            displayedCount = count<br>        }<br>    }<br>}</pre><p>I felt a huge improvement. The logic and the UI were separated, and the presenter is testable too. But the code contained too much boilerplate. Boilerplate refers to a standardized, reusable text, code, or form that can be incorporated into new documents or applications without major changes.</p><h4>PROS:</h4><p>&gt; Clean separation</p><p>&gt; highly testable</p><h4>CONS:</h4><p>&gt; Boilerplate heavy</p><p>&gt; manual lifecycle handling</p><p>&gt; verbose for simple features.</p><p>Just like how annoyed you would get when your friend has to reconsult everything, the same applies to interfaces, callbacks (detach()), etc.</p><h3>MVVM — Model View ViewModel — “Let the others handle it.”</h3><p>The UI reacts to the state. This is like a proper leader of your project who will be getting updates and transferring these updates to a different team. The view model holds the state, the view observes it. Therefore, no direct communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*P4rTL5jNMftSvt4EMoDqpQ.png" /></figure><pre>private val _uiState = MutableStateFlow(CounterUiState())<br>val uiState = _uiState.asStateFlow()<br>fun increment() {<br>    _uiState.update { it.copy(count = it.count + 1) }<br>}<br>In Compose<br>val state by vm.uiState.collectAsStateWithLifecycle()<br><br>Text(text = state.count.toString())<br><br>Button(onClick = vm::increment)</pre><p>This handles rotation and lifecycle.</p><h4>PROS:</h4><p>&gt; Clean and scalable</p><p>&gt; Lifecycle aware</p><p>&gt; Less boilerplate than MVP</p><p>This is the point you will actually start making sense of the Android architecture.</p><h3>MVI — Model View Intent</h3><p>This is that strict friend of yours who cannot cross rules. Everything flows in one direction only. The UI cannot change state directly ever. It must send an intent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*bSFGBQdzIhOdQHgTZif7ew.png" /></figure><pre>Step 1: Define Intents<br>sealed class CounterIntent {<br>    object Increment : CounterIntent()<br>    object Decrement : CounterIntent()<br>    object Reset     : CounterIntent()<br>}<br>Step 2: Define State<br>data class CounterState(<br>    val count: Int = 0,<br>    val isLoading: Boolean = false,<br>    val errorMessage: String? = null<br>)<br>Step 3: Reducer in ViewModel<br>fun process(intent: CounterIntent) {<br>    _state.update { current -&gt; reduce(current, intent) }<br>}<br>private fun reduce(state: CounterState, intent: CounterIntent): CounterState =<br>    when (intent) {<br>        CounterIntent.Increment -&gt; state.copy(count = state.count + 1)<br>        CounterIntent.Decrement -&gt; state.copy(count = state.count - 1)<br>        CounterIntent.Reset     -&gt; state.copy(count = 0)<br>    }<br>In Compose<br>Button(onClick = { onIntent(CounterIntent.Increment) })</pre><p>This felt extremely structured. It was a framework, not just an app. Every action is explicit, and every state change is predictable. This feels stringent. We know that a friend is doing for the good, but it would be fun to let loose at times.</p><h4>PROS:</h4><p>&gt; Predictable</p><p>&gt; single source of truth</p><p>&gt; great for complex apps</p><h4>CONS:</h4><p>&gt; Verbose</p><p>&gt; steep learning curve</p><p>&gt; overkill for small apps</p><p>What made this experiment powerful for me wasn’t the theory.</p><p>It was switching between tabs in my app:</p><ul><li>MVC → everything inside Composable</li><li>MVP → Presenter in control</li><li>MVVM → state-driven UI</li><li>MVI → intent-driven system</li></ul><p>Same UI.<br>Same feature.<br>Different mental models.</p><h3>What Actually Changed for Me</h3><ul><li><strong>MVC</strong> → “This is easy” → became messy fast</li><li><strong>MVP</strong> → “This is structured” → too much boilerplate</li><li><strong>MVVM</strong> → “This feels right” → balanced and practical</li><li><strong>MVI</strong> → “This is powerful” → but heavy</li></ul><p>Do let me know what you think of this !!! Do checkout the code structure in github: <a href="https://github.com/Kritzr/archidemo1/tree/master">https://github.com/Kritzr/archidemo1/tree/master</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b5757c8fbfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Activity to Process Death: Understanding ViewModel Through the Android Lifecycle Internals]]></title>
            <link>https://medium.com/@kritstudy15/from-activity-to-process-death-understanding-viewmodel-through-the-android-lifecycle-internals-eee6954d9ceb?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/eee6954d9ceb</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 09:28:15 GMT</pubDate>
            <atom:updated>2026-02-27T09:28:15.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqME-8obAgw9rVPx2ZHi6w.png" /></figure><p>Android apps have two main layers → the UI Layer, which contains the elements that are presented to the user. We also have the data layer — which has the data retrieved from the repositories. But when the Screen changes, we will have too change both the UI Elemens and the data present in there. That is where we have the viewmodels.</p><h3>What Is a ViewModel Really?</h3><p>View models are a class defined to handle the business logic and the screen level stateholder. It gives the state to the UI. It encapslated the business logic, and caches the state and persists through the configurational changes. When the UI directly holds the state, it becomes harder while navigating. it is convinient API for data persistence.</p><h3>Why ViewModel Survives Screen Rotation?</h3><p>This means that, it can handles the screen rotation that usually causes a configuration change that destroys and recreates the Activity, typically causing data loss. A viewmodel solves this by surviving the rotation as its lifecycle lasts from when an activity is first created until it is finished, ensuring UI data remians intact and available to the new activity instance.</p><p>It works because ViewModel instances are stored inside a container called ViewModelStore. During these configuration changes, this ViewModelStore is retained. The new Activity instance receives the same ViewModel instance. So while the Activity object changes, the ViewModel object does not.</p><p>This prevents data loss, unnecessay DB Queries, repeated network calls and ensures a seamless user experience.</p><p>A ViewModel survives rotation because it is intentionally designed by the Android framework to outlive the Activity or Fragment instances it is associated with during configuration changes. This mechanism prevents the loss of UI-related data and unnecessary data re-fetching when the screen is rotated.</p><p>A ViewModel does not survive process death because it is stored only in the application&#39;s RAM, which is completely wiped out when the Android system terminates the app&#39;s process.</p><p>Key Reasons</p><ul><li><strong>Memory-Based Storage</strong>: The ViewModel instances are held in memory within a special container called ViewModelStore. During configuration changes (like screen rotation), the Activity instance is destroyed, but the ViewModelStore is retained in a NonConfigurationInstance object in memory and passed to the new Activity instance.</li><li><strong>Process Termination</strong>: When the Android OS needs to free up resources, it can kill the entire application process, especially if the app is in the background. This termination is a complete system action that clears all memory associated with the process.</li><li><strong>No Serialization</strong>: ViewModel objects themselves are not automatically serialized to disk or any persistent storage. Since they only exist in RAM, they are lost when the process is killed.</li></ul><h3>The Internal Mechanism Behind Retention</h3><p>When a configuration change occurs, Android performs the following sequence:</p><h4>1. Activity Destruction</h4><p>The current Activity instance is destroyed.<br> onDestroy() is called.</p><h4>2. ViewModelStore Retention</h4><p>The ViewModel is not destroyed.</p><p>Internally, Android retains the ViewModelStore using a special mechanism inside ComponentActivity. Historically, this relied on onRetainNonConfigurationInstance(), but today the process is handled automatically by the architecture components.</p><h4>3. Activity Recreation</h4><p>A new Activity instance is created to match the new configuration.</p><h4>4. ViewModel Reuse</h4><p>The new Activity calls:</p><pre>val vm = ViewModelProvider(this)[MyViewModel::class.java]</pre><p>The ViewModelProvider checks the ViewModelStore:</p><ul><li>If an instance exists → it returns it.</li><li>If not → it creates a new one.</li></ul><p>Since the store was retained, the existing ViewModel is reused.</p><p>No serialization.<br> No disk persistence.<br> Just memory retention inside the same process.</p><h3>Why ViewModel Does NOT Survive Process Death</h3><p>This is where many developers misunderstand its purpose.</p><p>A ViewModel survives rotation because the process is still alive.</p><p>But when the Android OS kills the application process:</p><ul><li>All RAM associated with the process is cleared.</li><li>Every object in memory is destroyed.</li><li>The ViewModelStore is gone.</li><li>The ViewModel instance is gone.</li></ul><p>When the user reopens the app:</p><ul><li>A brand new process is created.</li><li>A new Activity is created.</li><li>A new ViewModel is created.</li></ul><p>The previous state is permanently lost.</p><h3>Key Reasons ViewModel Cannot Survive Process Death</h3><h4>1. Memory-Based Storage</h4><p>ViewModel exists only in RAM. It is not written to disk.</p><h4>2. Process Termination Is Absolute</h4><p>When Android needs memory, it can terminate background processes completely. This is not a lifecycle event — it is a system-level kill.</p><h4>3. No Automatic Serialization</h4><p>ViewModel objects are not serialized automatically. They are not persisted to disk unless you explicitly store the data elsewhere.</p><p>This design keeps ViewModel lightweight and fast — but not persistent.</p><h3>When Is ViewModel Destroyed Permanently?</h3><p>A ViewModel’s onCleared() method is called only when its lifecycle owner is permanently finished.</p><p>For example:</p><ul><li>User presses Back or when,</li><li>finish() is called or when,</li><li>the Fragment is removed permanently</li></ul><p>At that point, the ViewModelStore clears the ViewModel instance and releases memory completely.</p><h3>Handling Process Death the Right Way</h3><p>Since ViewModel does not survive process death, what should you use?</p><p>For small UI state:</p><ul><li><strong>SavedStateHandle</strong></li><li>Saved Instance State Bundle</li></ul><p>For long-term or critical data:</p><ul><li>Room database</li><li>DataStore</li><li>Repository-backed persistence</li></ul><p>The correct architecture looks like this:</p><p>UI → ViewModel → Repository → Persistent Data Source</p><p>The ViewModel holds in-memory UI state.</p><p>The Repository ensures the state can be reconstructed after process death.</p><p>That is robust Android architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eee6954d9ceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMMON VULNERABILITIES IN ANDROID APPLICATIONS]]></title>
            <link>https://medium.com/@kritstudy15/common-vulnerabilities-in-android-applications-8320bbc19613?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8320bbc19613</guid>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 11:13:04 GMT</pubDate>
            <atom:updated>2026-02-23T11:13:04.257Z</atom:updated>
            <content:encoded><![CDATA[<p>Android OS powers billions of mobile devices around the world. Such a scale is always accompanied by risks. Most of the Android vulnerabilities don&#39;t only come from sophisticated and complicated security breaches, but also due to developer oversights. In this article, we will break down some of the most common and dangerous Android security vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*ctsIceC3h4wjwdbK.png" /><figcaption>ANDROID VULNERABILITITES (Src: OWASP Mobile Top 10)</figcaption></figure><p>Android application vulnerabilities mostly stem from insecure data storage, weak authentication, and improper communication (SSL/TLS), with over 80% of applications handling critical data flaws.</p><h3>KEY THREATS</h3><p>Threats include data leakage, unauthorized access (intent redirection), reverse engineering, and usage of outdated and insecure libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*u_GLUdla28xZE_-g-b2x3Q.png" /></figure><ol><li><strong>Insecure Data Storage (Highest Risk):</strong></li></ol><ul><li>Many apps store sensitive information like authentication tokens, financial records, cached API responses, or user data in plaintext, particularly in SQLite databases, which 82% of analysed apps failed to protect properly.</li><li>Most of the Android Apps use SQLite (via Room), which are not encrypted by default. This eases the attacker’s route to gain access to the rooted device, debug build, and backup extraction access.</li><li>We can prevent it by using encrypted storage (SQLCipher/encrypted Room), using Android Keystore for cryptographic keys, and not storing sensitive tokens.</li></ul><p><strong>2. Insecure Communication:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*nWufpF8rkNAEtaIUVWBLXQ.png" /></figure><ul><li>Applications often fail to validate SSL/TLS certificates, allowing attackers to perform <a href="https://www.hackingloops.com/most-critical-android-application-vulnerabilities/">man-in-the-middle attacks to steal data</a>. They mostly use HTTP (not even HTTPS).</li><li>This allows Man In the Middle (MITM) Attacks using BurpSuite/Wireshark to analyse the packet headers etc.,</li><li>We can prevent this by using HTTPS, Certificate pinning, and validating the tokens in the server side.</li></ul><p><strong>3. Improper Platform Usage:</strong></p><ul><li>Misuse of Android features like Intents, permissions, or storing data in public external storage instead of secure internal storage.</li><li>This includes the exported components abuse: if the app components are incorrectly marked as android:exported=&quot;true&quot;, Other apps can invoke them directly.</li><li>This allows navigation bypass, data access, and unauthorized actions. We can prevent this by auditing the manifest file.</li></ul><p><strong>4. Weak Authentication/Authorization:</strong></p><ul><li>Insecure <a href="https://www.youtube.com/watch?v=bVPZIfIGblo">direct object references (IDORs)</a> or improper token management can allow unauthorized users to access data.</li></ul><p><strong>5. Reverse Engineering:</strong></p><ul><li>Because Java bytecode is easy to decompile, attackers can reverse-engineer applications to uncover API keys, algorithms, and sensitive business logic.</li><li>These are done using tools such as APKTool and jadx. With minimal efforts, an attacker can view the business logic, inspect db schemas, extract API keys and hardcoded secrets.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_u08wjme-xEDaK2R1-Spyw.png" /></figure><ul><li>We can prevent this by enabling the R8/ProGuard obfuscation, avoiding hardcoding and move sensitive logic to servers.</li><li>We can prevent this by enabling the R8/ProGuard obfuscation, avoiding hardcoding and move sensitive logic to servers.</li></ul><p><strong>6. Input Validation Issues:</strong></p><ul><li><a href="https://www.youtube.com/watch?v=Oqmoff2DmFw">SQL injection</a> and other injection attacks occur when apps do not sanitize user input, allowing attackers to manipulate queries.</li><li><strong>Insecure WebViews:</strong></li><li>Improper configuration of WebViews can lead to <a href="https://theredteamlabs.com/vulnerabilities-in-android-apps-what-developers-need-to-know/">cross-site scripting (XSS)</a>.</li></ul><h3>WHAT IS ANDROID DOING TO PREVENT THIS?</h3><p><strong>Android Security Bulletin — December 2025</strong></p><p>What It Contains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqUsJ2Kp0JVddPW9h1g60A.png" /></figure><p><strong>(I) Security Patch Levels:</strong></p><ul><li>Android devices with <strong>2025–12–01</strong> patch level include fixes for the vulnerabilities listed.</li><li>Devices with <strong>2025–12–05</strong> patch level include those fixes plus additional patches (especially kernel and vendor component fixes).</li></ul><p><strong>(II) Key Points:</strong></p><p>Google publishes a bulletin every month describing security flaws found in Android and fixes released to address them. Vulnerabilities are categorized by component, such as: framework, system, kernel, Hardware vendor components (Qualcomm, Unisoc, Mali, etc.)</p><p><strong>Notable Highlights</strong></p><ul><li>The bulletin documents <strong>multiple high-severity issues</strong> (e.g., elevation of privilege, information disclosure).</li><li>The most severe can lead to <strong>remote denial of service</strong> or allow attackers to escalate privileges <strong>without additional permissions</strong>.</li><li>Some vulnerabilities were observed under <strong>limited targeted exploitation</strong> — meaning attackers may already be using them in the wild.</li></ul><p>This bulletin is how Android:</p><ul><li>Tells device makers what vulnerabilities have been discovered</li><li>Documents which CVEs (Common Vulnerabilities and Exposures) are fixed</li><li>Helps users understand which security patch level they must be on for protection.</li></ul><p>It is a versatile command-line tool that facilitates communication between a computer and an Android device or emulator. It is primarily used by developers for debugging apps and accessing advanced device features, but it can also be a powerful tool for general users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hQF2S15QU0r20INb.jpeg" /></figure><p>ADB operates using a client-server architecture with three main components:</p><p>Android Developers</p><ul><li><strong>A client:</strong> Runs on your development machine (Windows, macOS, or Linux) and sends commands via a terminal.</li><li><strong>A daemon (adbd):</strong> A background process that runs on the Android device/emulator and executes the commands received from the client.</li><li><strong>A server:</strong> Runs as a background process on the development machine and manages the communication between the client and the daemon.</li></ul><p>REFERENCES:</p><ol><li><a href="https://ro.ecu.edu.au/cgi/viewcontent.cgi?params=/context/ism/article/1224/&amp;path_info=SECURITY_VULNERABILITIES_IN_ANDROID_APPLICATIONS.pdf">https://ro.ecu.edu.au/cgi/viewcontent.cgi?params=/context/ism/article/1224/&amp;path_info=SECURITY_VULNERABILITIES_IN_ANDROID_APPLICATIONS.pdf</a></li><li><a href="https://source.android.com/docs/security/bulletin/2025-12-01">https://source.android.com/docs/security/bulletin/2025-12-01</a></li><li><a href="https://source.android.com/docs/security/overview/updates-resources">https://source.android.com/docs/security/overview/updates-resources</a></li><li><a href="https://owasp.org/www-project-mobile-top-10/">https://owasp.org/www-project-mobile-top-10/</a></li><li><a href="https://apktool.org/docs/install/">https://apktool.org/docs/install/</a></li><li><a href="https://ro.ecu.edu.au/cgi/viewcontent.cgi?params=/context/ism/article/1224/&amp;path_info=SECURITY_VULNERABILITIES_IN_ANDROID_APPLICATIONS.pdf">https://www.ijfmr.com/papers/2024/6/32931.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8320bbc19613" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BOOTING OF THE ANDROID PROCESS]]></title>
            <link>https://medium.com/@kritstudy15/booting-of-the-android-process-e0ea2c4b5b0f?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0ea2c4b5b0f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-internals]]></category>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 11:34:51 GMT</pubDate>
            <atom:updated>2026-02-18T11:34:51.224Z</atom:updated>
            <content:encoded><![CDATA[<p>When you tap an Android app icon, it feels instantaneous.</p><p>But under the hood, Android performs a highly optimized sequence of operations involving the Linux kernel, the Android Runtime (ART), the Activity Manager Service, and a special process called <em>Zygote</em>.</p><p>Let’s break down what really happens — from installation to process creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3g11DomCYsSB3WTLIPZUtQ.png" /><figcaption>Fig 01: Summarising the article</figcaption></figure><h3><strong>What is being installed?</strong></h3><p>Android apps are typically written in Kotlin (or Java) and are delivered as either:<br> → .apk (<strong>Android Package</strong>): contains everything required to run the app.</p><p>→ .aab(<strong>Android App Bundle</strong>): contains the metadata used by Google Play to generate device-specific APKs.</p><p>These contain the SDK tools necessary for the code as well as the resource files such as images, layouts, strings, etc., compiled code, manifest files, and native libraries.</p><p>The Kotlin code is transformed into a<strong> Dalvik Executable bytecode (.dex)</strong>.</p><h3><strong>From the .dex to Native code</strong></h3><p>Android uses the <strong>Android Runtime (ART)</strong> to execute applications.</p><p>During installation:</p><ul><li>The .dex bytecode is compiled into <strong>native machine code</strong>.</li><li>The output is stored as <strong>OAT (Optimized Android Runtime) files</strong>.</li></ul><p>Android uses a hybrid compilation model:</p><ul><li><strong>AOT (Ahead-of-Time compilation)</strong> during installation.</li><li><strong>JIT (Just-In-Time compilation)</strong> for hot code paths during execution.</li></ul><p>This hybrid strategy improves:</p><ul><li>Startup performance</li><li>Runtime efficiency</li><li>Battery optimization</li></ul><p>Android apps operate as an isolated process on top of the Linux kernel, which is managed by the nadroid run time and the activity manager service. Unlike most programs, Android apps do not have a single <em>main()</em> entry point; instead, they have components such as <strong>services</strong> and<strong> activities</strong> that are triggered based on the new activities the user navigates to.</p><h3><strong>Linux Sandbox Model:</strong></h3><p>When you install the Android app, the OSof your device assigns the app a unique Linux user ID- UID. This creates a separate, secure sandbox environment for the process. So this means that each application has its own dedicated Linux process.</p><p>Each process contains its own instance of the <strong>Android Runtime (ART),</strong> which executes the app’s code. (its own VM). During the installation of your app, this compiles the dex code into <strong>native machine code (OAT File)</strong> to speed up performance.</p><p>The Android system implements the <strong>principle of least privilege</strong> -&gt;</p><ul><li>An app can only access its own data and explicitly granted permissions.</li><li>It cannot access other apps’ data by default.</li></ul><p>However, it is feasible to make two apps share the same Linux User ID, to enable them to access each other’s files. This is also done for the case when the OStries to save the resources. The apps are signed with the same certificate. Two apps can communicate via<strong> Interprocess Communication (IPC) </strong>as well.</p><h3>No main() Function</h3><p>Unlike traditional programs, Android apps do <strong>not</strong> have a single main() entry point.</p><p>Instead, they are component-based systems:</p><ul><li>Activities</li><li>Services</li><li>Broadcast Receivers</li><li>Content Providers</li></ul><p>These components are triggered by:</p><ul><li>User interactions</li><li>System events</li><li>Intents</li></ul><p>The Android system decides when and how they start.</p><h3><strong>The Zygote — The Master Process</strong></h3><p>To launch the app and save the resources, Android forks from a parent process called the zygote.</p><p>When the Android OS boots:</p><ol><li>The Linux init process starts.</li><li>init launches a special process called <strong>Zygote</strong>.</li><li>Zygote preloads:</li></ol><ul><li>Core framework classes</li><li>Common resources</li><li>System libraries</li></ul><p>This helps in reloading these resources every time a new app starts.</p><p>When we click the app (to open it), the <strong>Activity Manager Service (AMS) </strong>of Android instructs the zygote to fork itself. The AMS checks whether the app process is already running. If not, the AMS instructs Zygote to fork itself.</p><p>The “new app” inherits the preloaded data using copy on write memory management technique, making the creation of this process instantaneous. The memory pages are only copied if modified, and this makes the process creation extremely fast and memory efficient.</p><h3><strong>Process Priority &amp; Memory Management</strong></h3><p>The Android OS prioritises performance and battery life over keeping the app running and alive. So it uses a hierarchy to categorise the apps based on the user visibility and classifies them as :</p><ul><li><strong>Foreground Process:</strong> App is currently on screen and active (Highest Priority).</li><li><strong>Visible Process:</strong> App is visible but not in focus (e.g., a dialog is on top).</li><li><strong>Service Process:</strong> App is doing background work (e.g., streaming music).</li><li><strong>Cached Process:</strong> App is in the background and can be killed to free up RAM (Lowest Priority).</li><li><strong>Low-Memory Killer:</strong> When RAM is scarce, the Linux kernel, instructed by the Low Memory Killer, terminates processes starting from the bottom of the priority list. This is why background apps sometimes restart when reopened.</li></ul><p>In the upcoming articles, we will dive deeper into the app components, caching, boot optimization, and mechanisms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0ea2c4b5b0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Kotlin Coroutines Through My First Android Authentication Flow]]></title>
            <link>https://medium.com/@kritstudy15/understanding-kotlin-coroutines-through-my-first-android-authentication-flow-e315659573fc?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e315659573fc</guid>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 11:17:18 GMT</pubDate>
            <atom:updated>2026-02-09T11:17:18.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GBTnPMZGhmysFkH1" /><figcaption>Fig 01: Threads and Coroutines</figcaption></figure><p>I still remember the first time I saw “Application Not Responding” pop up on my app. I was making a simple database query on the main thread, and boom — frozen screen, angry dialog, frustrated user (me).</p><p>That’s when I finally sat down to learn Kotlin Coroutines properly. Not by reading documentation for hours, but by building something real: a signup and login system for my app.</p><p>Here’s what I learned along the way.</p><h3>The Problem: Your Main Thread Hates You</h3><p>Every Android app has a main thread — the UI thread. It’s responsible for drawing your app, handling touches, and keeping everything smooth. When you force it to do heavy work like database queries or network calls, it freezes. Your app stutters. Users get annoyed. Sometimes Android just kills your app entirely with an ANR error.</p><p>For years, Android developers dealt with this using AsyncTask (which is now deprecated), messy callback chains that made code hard to read, or libraries like RxJava that felt like overkill for simple tasks.</p><p>Coroutines changed everything.</p><h3>So What Actually Is a Coroutine?</h3><p>Here’s the simplest way I can explain it: a coroutine is a lightweight task that can pause its work, let other things happen, and then resume later — all without blocking your UI.</p><p>Think of it like this: You tell your app to fetch something from the database. Instead of standing there waiting for the result (blocking), your app says “cool, I’ll check back later” and keeps the UI responsive. When the data is ready, the coroutine picks up where it left off.</p><p>The best part? Your code still looks sequential and easy to read. No callback pyramids of doom.</p><h3>How I Used Coroutines in My App</h3><p>I built a basic authentication system with Room database, a ViewModel, and coroutines handling all the background work. The architecture looks like this:</p><ul><li>User taps a button in the UI</li><li>ViewModel launches a coroutine</li><li>Repository/DAO does the database work</li><li>Result flows back to the UI</li></ul><p>Everything stays smooth because the heavy lifting happens off the main thread.</p><h3>The Magic of viewModelScope</h3><p>In my AuthViewModel, I use viewModelScope.launch {} to start coroutines. This single line does something really smart: it ties the coroutine&#39;s lifecycle to the ViewModel. When the ViewModel gets destroyed (like when the user closes the screen), any running coroutines automatically get cancelled. No memory leaks, no background work running when it shouldn&#39;t.</p><pre>class AuthViewModel(application: Application) : AndroidViewModel(application) {<br>    private val userDao = TricountDatabase.getDatabase(application).userDao()<br>    <br>    fun signUp(name: String, email: String, password: String) {<br>        viewModelScope.launch {<br>            // All the background work happens here<br>        }<br>    }<br>}</pre><p>That’s it. No manual cleanup, no complicated threading logic.</p><h3>Building the Signup Flow</h3><p>Let me walk you through how signup actually works in my app. When a user clicks the Sign Up button:</p><ol><li>The ViewModel launches a coroutine</li><li>We validate the input fields</li><li>Check if the email already exists in the database</li><li>Insert the new user</li><li>Save their session</li><li>Update the UI with the result</li></ol><p>Here’s the actual code:</p><pre>fun signUp(name: String, email: String, password: String) {<br>    viewModelScope.launch {<br>        if (name.isBlank() || email.isBlank() || password.isBlank()) {<br>            _authResult.value = AuthResult.Error(&quot;All fields are required&quot;)<br>            return@launch<br>        }<br>        <br>        val existingUser = userDao.getUserByEmail(email)<br>        if (existingUser != null) {<br>            _authResult.value = AuthResult.Error(&quot;Email already registered&quot;)<br>            return@launch<br>        }<br>        <br>        val newUser = UserEntity(<br>            name = name,<br>            email = email,<br>            password = password<br>        )<br>        val userId = userDao.insertUser(newUser).toInt()<br>        <br>        sessionManager.saveSession(userId, email, name)<br>        _authResult.value = AuthResult.Success(userId)<br>    }<br>}</pre><p>The beautiful thing here is that getUserByEmail() and insertUser() are database operations. They could take a few milliseconds or longer, but because they&#39;re inside a coroutine, Room automatically runs them off the main thread. The UI never freezes.</p><h3>Login Works the Same Way</h3><p>The login flow follows the same pattern but simpler:</p><pre>fun login(email: String, password: String) {<br>    viewModelScope.launch {<br>        if (email.isBlank() || password.isBlank()) {<br>            _authResult.value = AuthResult.Error(&quot;Email and password are required&quot;)<br>            return@launch<br>        }<br>        <br>        val user = userDao.login(email, password)<br>        if (user != null) {<br>            sessionManager.saveSession(user.id, user.email, user.name)<br>            _authResult.value = AuthResult.Success(user.id)<br>        } else {<br>            _authResult.value = AuthResult.Error(&quot;Invalid credentials&quot;)<br>        }<br>    }<br>}</pre><p>Again, the database query happens in the background, and the UI just reacts to the result when it’s ready.</p><h3>Making the UI Reactive with StateFlow</h3><p>I paired coroutines with StateFlow to make the UI automatically respond to authentication results:</p><pre>private val _authResult = MutableStateFlow&lt;AuthResult?&gt;(null)<br>val authResult: StateFlow&lt;AuthResult?&gt; = _authResult</pre><p>The pattern is simple: the coroutine updates _authResult when work completes, and the UI observes authResult to show success messages, error dialogs, or navigate to the next screen.</p><p>This creates a clean separation between the background work (in coroutines) and the UI updates (through StateFlow).</p><h3>What I Actually Learned</h3><p>After building this authentication system, a few things became really clear:</p><p><strong>Coroutines make async code readable.</strong> I can write code that looks like it runs line by line, even though it’s actually doing background work. No nested callbacks, no confusing thread management.</p><p><strong>viewModelScope is genuinely helpful.</strong> Not having to worry about cancelling coroutines manually or dealing with memory leaks is such a relief.</p><p><strong>They work beautifully with Room and StateFlow.</strong> The whole modern Android stack is designed to work together, and coroutines are the glue that makes it smooth.</p><p><strong>Debugging is so much easier.</strong> When something goes wrong, I can follow the code flow naturally instead of jumping through callback chains.</p><h3>Why You Should Learn Coroutines</h3><p>If you’re building any Android app that does real work — talking to a database, making network calls, handling authentication, processing files — you need coroutines. They’re not optional anymore. They’re how modern Android development works.</p><p>And honestly? The best way to learn them isn’t by reading documentation. Build something. A simple login screen, a notes app, anything that touches a database. Use viewModelScope, launch some coroutines, break things, add logs everywhere, and see what happens.</p><p>That’s how I learned, and now I can’t imagine going back to the old way of doing things.</p><p>The main thread thanks me every day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e315659573fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Android Launch Modes: A Deep Dive into Activity Stack Management]]></title>
            <link>https://medium.com/@kritstudy15/mastering-android-launch-modes-a-deep-dive-into-activity-stack-management-3c914946e1f7?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c914946e1f7</guid>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 11:19:41 GMT</pubDate>
            <atom:updated>2026-02-04T11:19:41.222Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding how Android manages activities is crucial for building robust applications with seamless navigation. Launch modes and task management are fundamental concepts that every Android developer must master to create intuitive user experiences and prevent common navigation pitfalls.</p><h3>What Are Launch Modes?</h3><p>Launch modes are configurations that determine how an activity is launched and how it interacts with the existing activity stack. These configurations are primarily defined in the AndroidManifest.xml file using the launchMode attribute, though they can also be controlled dynamically through intent flags.</p><p>Think of launch modes as rules that govern whether Android should create a new instance of an activity, reuse an existing one, or clear the stack altogether.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GH_YBTnNoeQPeclZ_gqozQ.png" /><figcaption>Fig 01: Launch modes</figcaption></figure><h3>The Four Launch Modes Explained</h3><h3>1. Standard (Default Behavior)</h3><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    android:launchMode=&quot;standard&quot; /&gt;</pre><p><strong>Behavior:</strong></p><ul><li>Every time the activity is launched, a new instance is created and pushed onto the stack</li><li>Even if an identical instance already exists at the top of the stack, Android creates a new one</li><li>This is the default mode when no launchMode is specified</li></ul><p><strong>Use Case:</strong> Most activities in your app, especially those that display different data each time (like a product detail page)</p><p><strong>Potential Issue:</strong> Can lead to multiple instances of the same activity, potentially causing memory issues</p><h3>2. SingleTop</h3><pre>&lt;activity<br>    android:name=&quot;.SearchActivity&quot;<br>    android:launchMode=&quot;singleTop&quot; /&gt;</pre><p><strong>Behavior:</strong></p><ul><li>If the activity is already at the top of the stack, no new instance is created</li><li>Instead, the existing instance receives the new intent through the onNewIntent() callback</li><li>If the activity exists but is not at the top, a new instance is created</li></ul><p><strong>Implementation:</strong></p><pre>@Override<br>protected void onNewIntent(Intent intent) {<br>    super.onNewIntent(intent);<br>    // Handle the new intent here<br>    setIntent(intent);<br>    processIntent(intent);<br>}</pre><p><strong>Use Case:</strong> Search activities, notification handlers, or any activity that should update its content when launched again from the top</p><h3>3. SingleTask</h3><pre>&lt;activity<br>    android:name=&quot;.DashboardActivity&quot;<br>    android:launchMode=&quot;singleTask&quot; /&gt;</pre><p><strong>Behavior:</strong></p><ul><li>Only one instance of the activity exists in the system</li><li>If no instance exists, Android creates one</li><li>If an instance already exists:</li><li>The task containing that activity is brought to the foreground</li><li>All activities above it in the stack are cleared</li><li>The existing instance receives the new intent via onNewIntent()</li></ul><p><strong>Use Case:</strong> Main dashboard, home screens, or activities that serve as entry points to major app sections</p><p><strong>Important Note:</strong> This mode works in conjunction with taskAffinity. Without a specific affinity, it might not create a new task as expected.</p><h3>4. SingleInstance</h3><pre>&lt;activity<br>    android:name=&quot;.ShareActivity&quot;<br>    android:launchMode=&quot;singleInstance&quot; /&gt;</pre><p><strong>Behavior:</strong></p><ul><li>Creates a new task and ensures the activity is the only one in that task</li><li>No other activities can be launched into the same task</li><li>Any new activity launched from this activity opens in a different task</li></ul><p><strong>Use Case:</strong> Specialized screens like share dialogs, login screens, or activities that need complete isolation</p><h3>Understanding Tasks and the Back Stack</h3><h3>What is a Task?</h3><p>A <strong>task</strong> is a collection of activities that users interact with when performing a specific job. These activities are arranged in a <strong>back stack</strong>, following the Last-In-First-Out (LIFO) principle.</p><pre>┌─────────────────────────┐<br>│   Current Activity (C)  │  ← Top of stack<br>├─────────────────────────┤<br>│      Activity B         │<br>├─────────────────────────┤<br>│      Activity A         │  ← Root activity<br>└─────────────────────────┘</pre><h3>Root Launcher Activity</h3><p>The root activity is defined by intent filters in the manifest:</p><pre>&lt;activity android:name=&quot;.MainActivity&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br>        &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/activity&gt;</pre><ul><li>ACTION_MAIN: Entry point to the app</li><li>CATEGORY_LAUNCHER: Makes the activity appear in the launcher</li></ul><h3>Key Principle</h3><p>Activities in the back stack are <strong>never rearranged</strong>. If your app allows users to start a particular activity from multiple places, a new instance is created and pushed onto the stack rather than bringing an existing instance to the top (unless using special launch modes).</p><h3>Advanced Task Management</h3><h3>Manifest Attributes</h3><p>Beyond launchMode, you can control task behavior with these attributes:</p><h4>1. taskAffinity</h4><pre>&lt;activity<br>    android:name=&quot;.EmailActivity&quot;<br>    android:taskAffinity=&quot;com.example.email&quot; /&gt;</pre><p>Defines which task an activity belongs to. Activities with the same affinity belong to the same task.</p><h4>2. allowTaskReparenting</h4><pre>&lt;activity<br>    android:name=&quot;.ShareActivity&quot;<br>    android:allowTaskReparenting=&quot;true&quot; /&gt;</pre><p>Allows an activity to move from one task to another when the task it has an affinity with comes to the foreground.</p><h4>3. clearTaskOnLaunch</h4><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    android:clearTaskOnLaunch=&quot;true&quot; /&gt;</pre><p>Clears all activities from the task except the root activity whenever the user leaves and returns to the task.</p><h4>4. alwaysRetainTaskState</h4><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    android:alwaysRetainTaskState=&quot;true&quot; /&gt;</pre><p>Preserves the complete task state regardless of how long the user has been away (opposite of default behavior).</p><h4>5. finishOnTaskLaunch</h4><pre>&lt;activity<br>    android:name=&quot;.TempActivity&quot;<br>    android:finishOnTaskLaunch=&quot;true&quot; /&gt;</pre><p>Causes the activity to be finished whenever the user leaves and returns to the task.</p><h3>Intent Flags</h3><p>Intent flags provide dynamic control over launch behavior at runtime:</p><h4>1. FLAG_ACTIVITY_NEW_TASK</h4><pre>Intent intent = new Intent(this, TargetActivity.class);<br>intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<br>startActivity(intent);</pre><p>Starts the activity in a new task or finds an existing task with matching affinity.</p><h4>2. FLAG_ACTIVITY_CLEAR_TOP</h4><pre>Intent intent = new Intent(this, MainActivity.class);<br>intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);<br>startActivity(intent);</pre><p>If the target activity already exists in the stack, all activities above it are destroyed.</p><h4>3. FLAG_ACTIVITY_SINGLE_TOP</h4><pre>Intent intent = new Intent(this, CurrentActivity.class);<br>intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);<br>startActivity(intent);</pre><p>Equivalent to singleTop launch mode, but applied dynamically.</p><h3>Manifest vs. Intent Flags: Which Takes Priority?</h3><p>This is a critical point that often confuses developers:</p><p><strong>The Rule:</strong> Intent flags <strong>override</strong> manifest attributes when they conflict.</p><p>Example:</p><pre>&lt;!-- Manifest --&gt;<br>&lt;activity<br>    android:name=&quot;.MyActivity&quot;<br>    android:launchMode=&quot;standard&quot; /&gt;</pre><pre>// Runtime - This takes priority<br>Intent intent = new Intent(this, MyActivity.class);<br>intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);<br>startActivity(intent);</pre><p>In this case, the activity behaves as singleTop despite being declared as standard in the manifest.</p><p><strong>Best Practice:</strong> Use manifest attributes for default behavior and intent flags for special cases that require runtime decisions.</p><h3>“Up” vs. “Back” Navigation</h3><p>Understanding the difference between these navigation patterns is essential for proper UX:</p><h3>Back Navigation</h3><ul><li>Navigates <strong>chronologically</strong> through the back stack</li><li>Follows the temporal order in which activities were opened</li><li>Behavior: Press back → return to the previous screen in history</li></ul><h3>Up Navigation</h3><ul><li>Navigates <strong>hierarchically</strong> through the app structure</li><li>Defined by the app’s logical structure, not temporal order</li><li>Implemented via the toolbar’s back arrow</li><li>Defined in manifest:</li></ul><pre>&lt;activity<br>    android:name=&quot;.DetailActivity&quot;<br>    android:parentActivityName=&quot;.MainActivity&quot; /&gt;</pre><h3>How Launch Modes Affect Navigation</h3><p><strong>SingleTask Issue:</strong> When using singleTask, the behavior can surprise users. If Activity A launches Activity B (singleTask), which then launches Activity C, pressing &quot;Up&quot; from C might clear the stack back to B, not following the user&#39;s expected path.</p><p><strong>Example:</strong></p><pre>User Journey: Home → Products → ProductDetail<br>Launch Mode: ProductDetail is singleTask</pre><pre>Expected on &quot;Up&quot;: Return to Products<br>Actual Behavior: Clears to ProductDetail&#39;s task root</pre><h3>Clearing the Stack on Return</h3><p>Android has built-in behavior for managing long-lived tasks:</p><h3>Default Behavior</h3><p>If a user leaves a task for an extended period (typically 30 minutes), Android clears the stack down to the root activity. This prevents users from returning to potentially stale or irrelevant screens.</p><h3>Controlling This Behavior</h3><p><strong>Prevent Clearing:</strong></p><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    android:alwaysRetainTaskState=&quot;true&quot; /&gt;</pre><p>Keeps the entire stack intact indefinitely.</p><p><strong>Force Clearing:</strong></p><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    android:clearTaskOnLaunch=&quot;true&quot; /&gt;</pre><p>Clears the stack every time the user returns, regardless of time away.</p><h3>Common Pitfalls and How to Avoid Them</h3><h3>1. The Duplicate Activity Bug</h3><p><strong>Problem:</strong> Using standard launch mode carelessly can create multiple instances of the same activity, leading to:</p><ul><li>Memory leaks</li><li>Confusing navigation (pressing back multiple times through identical screens)</li><li>Wasted resources</li></ul><p><strong>Solution:</strong></p><pre>// Check if activity already exists<br>Intent intent = new Intent(this, DetailsActivity.class);<br>intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);<br>startActivity(intent);</pre><h3>2. Task Affinity Misunderstandings</h3><p><strong>Problem:</strong> Developers expect singleTask to create a new task, but it doesn&#39;t if taskAffinity isn&#39;t properly defined.</p><p><strong>Default Behavior:</strong> All activities in an app have the same affinity (the package name) by default.</p><p><strong>Solution:</strong></p><pre>&lt;activity<br>    android:name=&quot;.IsolatedActivity&quot;<br>    android:launchMode=&quot;singleTask&quot;<br>    android:taskAffinity=&quot;com.example.isolated&quot; /&gt;</pre><h3>3. Memory Leaks from Static References</h3><p><strong>Problem:</strong> Reusing activity instances (singleTop, singleTask) can cause issues if you’re not careful with onNewIntent().</p><p><strong>Solution:</strong></p><pre>@Override<br>protected void onNewIntent(Intent intent) {<br>    super.onNewIntent(intent);<br>    setIntent(intent); // Update the intent<br>    <br>    // Clean up old resources<br>    cleanupPreviousState();<br>    <br>    // Process new intent<br>    processNewData(intent);<br>}</pre><h3>4. Ignoring Configuration Changes</h3><p><strong>Problem:</strong> Launch modes don’t prevent activities from being destroyed during configuration changes (rotation, language change).</p><p><strong>Solution:</strong> Handle configuration changes properly:</p><pre>&lt;activity<br>    android:name=&quot;.MyActivity&quot;<br>    android:configChanges=&quot;orientation|screenSize&quot; /&gt;</pre><p>Or save state properly:</p><pre>@Override<br>protected void onSaveInstanceState(Bundle outState) {<br>    super.onSaveInstanceState(outState);<br>    outState.putString(&quot;key&quot;, value);<br>}</pre><h3>Debugging Task and Activity Stacks</h3><h3>The Essential Debugging Command</h3><pre>adb shell dumpsys activity activities</pre><p>This command provides a detailed view of:</p><ul><li>All running tasks</li><li>Activity stack for each task</li><li>Launch modes</li><li>Intent flags</li><li>Task affinities</li></ul><h3>Sample Output Analysis</h3><pre>ACTIVITY MANAGER ACTIVITIES<br>  Stack #0:<br>    Task id #123<br>      * TaskRecord{abc MainActivity}<br>        * ActivityRecord{def MainActivity}<br>    Running activities:<br>      * ActivityRecord{ghi DetailActivity}<br>      * ActivityRecord{def MainActivity}</pre><h3>Useful Filtering</h3><pre># Show only your app&#39;s activities<br>adb shell dumpsys activity activities | grep com.yourpackage</pre><pre># Show current top activity<br>adb shell dumpsys activity activities | grep &quot;mResumedActivity&quot;</pre><h3>Best Practices and Recommendations</h3><h3>1. Start with Standard</h3><p>Use standard for most activities unless you have a specific reason not to.</p><h3>2. Document Your Decisions</h3><pre>&lt;!-- Using singleTask because this is the main dashboard<br>     that should clear intermediary activities when returned to --&gt;<br>&lt;activity<br>    android:name=&quot;.DashboardActivity&quot;<br>    android:launchMode=&quot;singleTask&quot; /&gt;</pre><h3>3. Test Navigation Thoroughly</h3><ul><li>Test back navigation</li><li>Test up navigation</li><li>Test deep links</li><li>Test after configuration changes</li><li>Test after the app has been in the background</li></ul><h3>4. Use Intent Flags for Dynamic Behavior</h3><p>Reserve manifest settings for default behavior and use intent flags when runtime decisions are needed.</p><h3>5. Consider User Experience</h3><p>Ask yourself:</p><ul><li>What would users expect when they press back?</li><li>Should this screen appear multiple times in the stack?</li><li>What happens if they’ve been away for 30 minutes?</li></ul><h3>Conclusion</h3><p>Launch modes and task management are powerful tools in Android development, but they require careful consideration. Understanding how activities are created, reused, and destroyed is essential for building apps with intuitive navigation and efficient resource usage.</p><p>Remember:</p><ul><li>Choose launch modes based on your specific use case</li><li>Intent flags override manifest settings</li><li>Test your navigation flows thoroughly</li><li>Use debugging tools to verify behavior</li><li>Always consider the user experience</li></ul><p>By mastering these concepts, you’ll build Android apps that feel natural, perform efficiently, and provide users with a seamless navigation experience.</p><h3><strong>Happy coding, and may your activity stacks always be properly managed!</strong></h3><p><em>Have questions about launch modes or task management? Drop a comment below, and let’s discuss!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c914946e1f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activity and Activity Lifecycles in Android]]></title>
            <link>https://medium.com/@kritstudy15/activity-and-activity-lifecycles-in-android-5c0e8b747847?source=rss-dba10a3097e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c0e8b747847</guid>
            <dc:creator><![CDATA[Krithika Ravishankar]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 07:11:42 GMT</pubDate>
            <atom:updated>2026-02-03T07:30:43.094Z</atom:updated>
            <content:encoded><![CDATA[<h3>WHAT IS AN ACTIVITY?</h3><p>So, when you first open an app, from where does the code start working?<br>In most of the programming languages, we have the main function or the main method via which the code starts, or it is the entry point for the compiler to understand where to start running the code from. But when it comes to Android, we have the activity class.</p><p>In Android, everything is handled as activities. We can have as many activities as we wish; the activities are stored in the back stack, and whichever is at the top is the one that is visible on the screen to the user.</p><p>Let us suppose you are trying to book a ticket. And in the payment section, it redirects to your payment gateway app (let us suppose Google Pay), the activity of your ticket booking app does not invoke the entirety of the Google Pay, instead it invokes the activity of that particular app. This activity renders the UI of that screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/0*DJLcelOXLKY1tGR5.png" /><figcaption>Fig 01: Navigation to other apps</figcaption></figure><p>When you open an app, you will see the main activity, which is the first screen that loads when you open the app. You may have multiple screens in the app that you would navigate, and that is accomplished by creating multiple activities.</p><p><em>You can add these activities as different files in your Android app. But how do you configure it?</em></p><h3>CONFIGURATION OF AN ACTIVITY:</h3><p>In your Android manifest.xml file, we declare the activity as a child of the application element. Let us suppose I want to add activity B and activity C. <br>We edit in the Android manifest.xml as:</p><pre>&lt;application<br>    android:allowBackup=&quot;true&quot;<br>    android:label=&quot;MyApp&quot;<br>    android:supportsRtl=&quot;true&quot;<br>    android:theme=&quot;@style/Theme.Myapp&quot;&gt;<br><br>    &lt;!-- Activity A (Launcher) --&gt;<br>    &lt;activity<br>        android:name=&quot;.MainActivity&quot;<br>        android:exported=&quot;true&quot;&gt;<br>        &lt;intent-filter&gt;<br>            &lt;action android:name=&quot;android.intent.action.MAIN&quot; android:launchMode=&quot;singleTask&quot; /&gt;<br>            &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>        &lt;/intent-filter&gt;<br>    &lt;/activity&gt;<br><br>    &lt;!-- Activity B --&gt;<br>    &lt;activity<br>        android:name=&quot;.ActivityB&quot;<br>        android:exported=&quot;false&quot; /&gt;<br><br>    &lt;!-- Activity C --&gt;<br>    &lt;activity<br>        android:name=&quot;.ActivityC&quot;<br>        android:exported=&quot;false&quot; /&gt;<br><br>&lt;/application&gt;</pre><p>The attribute <a href="https://developer.android.com/guide/topics/manifest/activity-element#nm">android: name</a> specifies the class name of the activity. We can also add multiple attributes, such as a label, depending on our app.</p><p>Another powerful attribute is the <a href="https://developer.android.com/guide/components/intents-filters">Intent filters</a>. They handle the launching of an activity based on an implicit request. As you can see from the above code, it is handled via the <a href="https://developer.android.com/guide/topics/manifest/action-element">&lt;action&gt;</a> element and a <a href="https://developer.android.com/guide/topics/manifest/category-element">&lt;category&gt;</a> element to specify the type of intent.</p><p>We can also provide permission to particular activities based on the <a href="https://developer.android.com/guide/topics/manifest/activity-element">&lt;activity&gt;</a> tag to control which apps can start a particular activity. A parent activity cannot launch a child activity unless both activities have the same permissions.</p><h3>STATES AND LIFECYCLE OF ACTIVITIES:</h3><p>As we navigate through our app, the activity undergoes several state changes. These are nothing but callbacks initiated by the activity class to let the activity know whether there is a state change or not. This state change helps us in saving the computing resources. For example, killing a process along with its activities depends on the state of the activity. When we navigate to another app, only partial resources are dismantled thanks to the states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/0*CtZDFNQ6VjZ6KZhg.png" /><figcaption>Fig 02: Visual represnetation of the states as described by android</figcaption></figure><h3>onCreate()</h3><p>This is the first state, when an activity is launched for the first time. This handles the startup logic of the app that happens once for the entire life of an activity, such as initialising the essential components.</p><p>We call the setContentView() to define the layout of our UI.</p><pre>// Overrides the Activity lifecycle method that is called when the Activity is first created<br>override fun onCreate(savedInstanceState: Bundle?) {<br><br>    // Calls the parent (Activity/AppCompatActivity) onCreate<br>    // This is required so the system can properly initialize the Activity<br>    super.onCreate(savedInstanceState)<br><br>    // Writes a debug log message for tracking lifecycle events in Logcat<br>    Log.d(TAG, &quot;onCreate&quot;)<br><br>    // Sets the UI content of this Activity using Jetpack Compose<br>    setContent {<br><br>        // Applies the custom Compose theme for the app<br>        MyappTheme {<br><br>            // Calls the composable function that represents Activity A&#39;s screen UI<br>            ActivityAScreen(<br><br>               <br>                randomNumber = viewModel.randomNumber,<br><br>            )<br>        }<br>    }<br>}</pre><p>Upon onCreate(), the app moves to onStart() and then to on Resume().</p><h3>onStart()</h3><p>As onCreate exits, the activity enters the started state, and the activity becomes visible to the user and becomes interactive with the user.</p><pre>// Called when the Activity becomes visible to the user<br>override fun onStart() {<br><br>    // Always call the superclass implementation first<br>    super.onStart()<br><br>    // Log message to indicate that onStart() has been triggered<br>    Log.d(TAG, &quot;onStart&quot;)<br><br>    // Example: Start or resume a task that should run while the Activity is visible (but not yet interactive)<br>    // e.g., registering a listener, starting animations, etc.<br><br>    // Example placeholder:<br>    // registerNetworkListener()<br>}</pre><h3>onResume()</h3><p>This callback is invoked just before the activity starts interacting with the user. The activity is at the top of the stack and captures all user input. When the user navigates out to another app (for example), the system invokes the onPause() callback, and when the user comes back, onResume() is called to reinitialise components that you release during onPause().</p><h3>onPause()</h3><p>The system calls <a href="https://developer.android.com/reference/android/app/Activity#onPause()">onPause()</a> when the activity loses focus and enters a Paused state. This state occurs when the user taps to navigate to another app or taps the back button. During this, the activity is partially visible, and it can go to onResume() or onStop().</p><p>We can use onPause() to release resources such as system resources, handles, etc., onPause cannot be used for saving data, like during transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NmTXEMmm53I0Gzqv" /><figcaption>Fig 03: Background apps</figcaption></figure><h3>onStop()</h3><p>The system calls <a href="https://developer.android.com/reference/android/app/Activity#onStop()">onStop()</a> when the activity is no longer visible to the user. This occurs when the process and the activity of that app are being destroyed, or when a new activity is starting. The next callback that the system calls is either <a href="https://developer.android.com/reference/android/app/Activity#onRestart()">onRestart()</a>if the activity is coming back to interact with the user, or by <a href="https://developer.android.com/reference/android/app/Activity#onDestroy()">onDestroy()</a> if this activity is completely gone.</p><h3>onRestart()</h3><p>The system invokes this callback when an activity in the Stopped state is about to restart. <a href="https://developer.android.com/reference/android/app/Activity#onRestart()">onRestart()</a> restores the state of the activity from the time that it was stopped.</p><p>This callback is always followed by <a href="https://developer.android.com/reference/android/app/Activity#onStart()">onStart()</a>.</p><h3>onDestroy()</h3><p>The system invokes this callback before an activity is destroyed. This is the last callback an activity receives. This means that the activity is finishing as the user closes the app, or when finish() is called, or when the system is destroying the activities due to configuration changes.</p><p>Let us consider an app with three activities, A, B and ,C. Let us try to log the activities via the logcat available in Android Studio:</p><pre>class ActivityAViewModel : ViewModel(){<br>    var randomNumber by mutableStateOf(0)<br>        private set<br><br>    init{<br>        generateRandom()<br>    }<br><br>    fun generateRandom(){<br>        randomNumber = (1..100).random()<br>    }<br><br>}<br>class MainActivity : ComponentActivity() {<br><br>    private val viewModel: ActivityAViewModel by viewModels()<br>    private val TAG =&quot;MainActivityLifeCycle&quot;<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        Log.d(TAG, &quot;onCreate&quot;)<br><br>        onBackPressedDispatcher.addCallback(this) {<br>            Log.d(TAG, &quot;Back pressed in Activity A → finish()&quot;)<br>            finish()<br>        }<br><br><br>        setContent {<br>            MyappTheme {<br>                ActivityAScreen(<br>                    randomNumber = viewModel.randomNumber,<br>                    onGoToB = {<br>                        startActivity(Intent(this, ActivityB::class.java))<br>                        finish() // close app flow<br>                    },<br>                    onGoToC = {<br>                        startActivity(Intent(this, ActivityC::class.java))<br>                    }<br>                )<br>            }<br>        }<br>    }<br><br><br>    override fun onStart() {<br>        super.onStart()<br>        Log.d(TAG, &quot;onStart&quot;)<br>    }<br><br>    override fun onResume() {<br>        super.onResume()<br>        Log.d(TAG, &quot;onResume&quot;)<br>    }<br><br>    override fun onPause() {<br>        super.onPause()<br>        Log.d(TAG, &quot;onPause&quot;)<br>    }<br><br>    override fun onStop() {<br>        super.onStop()<br>        Log.d(TAG, &quot;onStop&quot;)<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        Log.d(TAG, &quot;onDestroy&quot;)<br>    }<br><br>    override fun onRestart() {<br>        super.onRestart()<br>        Log.d(TAG, &quot;onRestart&quot;)<br>    }<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cG3Io5pRTwS8aCj_Y2yX8Q.png" /><figcaption>Fig 04: Accessing LogCat to view the logs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4kT9YiYj-Ylp9iFRUqj3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frMnofYtJd2huNWuyfGB6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1m1IqGG192E32cII1SubBA.png" /><figcaption>Fig 05: Logs of the lifecycle of an activity</figcaption></figure><p><em>Hope this gives you the insights on what an activity is, how to control its state, and its lifecycle!<br>There’s a lot more to explore around Activity launch behavior, lifecycle edge cases, and state management. What would you like to see covered next, and what’s tripped you up so far? Let me know in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c0e8b747847" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>