<?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 Android App Developer on Medium]]></title>
        <description><![CDATA[Stories by Android App Developer on Medium]]></description>
        <link>https://medium.com/@jayshritotewad?source=rss-a8ebd69e078a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s1WcnlqqZZCY--5eWxg2dQ.png</url>
            <title>Stories by Android App Developer on Medium</title>
            <link>https://medium.com/@jayshritotewad?source=rss-a8ebd69e078a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:44:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jayshritotewad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android Activities Under the Hood: The Definitive Systems-Level Guide]]></title>
            <link>https://medium.com/@jayshritotewad/android-activities-under-the-hood-the-definitive-systems-level-guide-dd14b37fbda2?source=rss-a8ebd69e078a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd14b37fbda2</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[death-process]]></category>
            <category><![CDATA[android-interviews]]></category>
            <category><![CDATA[senior-android-engineer]]></category>
            <category><![CDATA[android-activity]]></category>
            <dc:creator><![CDATA[Android App Developer]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 08:20:13 GMT</pubDate>
            <atom:updated>2026-02-17T08:20:13.673Z</atom:updated>
            <content:encoded><![CDATA[<h4>Most developers recite the lifecycle. Great engineers understand the state machine.</h4><p>Most Android developers can recite the lifecycle like a mantra: onCreate → onStart → onResume → onPause → onStop → onDestroy.</p><p>An Activity is not a standalone object; it is a <strong>client-side proxy</strong> for a state machine running in the Linux kernel and the System Server. Here is the architecture of what is actually happening behind the setContentView() curtain.</p><blockquote><strong>1. The Orchestrator: ActivityManagerService (AMS)</strong></blockquote><p>Your app process is fundamentally <em>dumb</em>. It does not know when it should start, stop, or die. Those decisions are made by the <strong>ActivityManagerService (AMS)</strong>, which lives in a completely different process called the system_server.</p><p>When you call startActivity(), you aren&#39;t invoking a method; you are performing an <strong>Inter-Process Communication (IPC)</strong> via <strong>Binder</strong>.</p><ul><li><strong>App Process:</strong> Calls Instrumentation.execStartActivity().</li><li><strong>Binder:</strong> Marshals the intent and sends it across process boundaries to the System Server.</li><li><strong>System Server (AMS):</strong> Validates the intent, checks permissions, and manages the Task Stack.</li><li><strong>Callback:</strong> The AMS sends a message back to your app’s ActivityThread saying: <em>Okay, launch this class now.</em></li></ul><blockquote><strong>2. The Heartbeat: ActivityThread &amp; The “H” Handler</strong></blockquote><p>Every Android app has a<em> Main Thread</em>. In the source code, this is ActivityThread.java.</p><p>The ActivityThread is essentially an infinite loop (Looper.loop()). It waits for messages from the System Server. These messages are processed by a mysterious internal class simply named <strong>H</strong>.</p><pre>// Simplified AOSP Source: ActivityThread.java<br>class ActivityThread {<br>    final H mH = new H();<br><br>    private class H extends Handler {<br>        public void handleMessage(Message msg) {<br>            switch (msg.what) {<br>                case EXECUTE_TRANSACTION:<br>                    // This is where onCreate, onStart, etc. are triggered<br>                    mTransactionExecutor.execute((ClientTransaction)msg.obj);<br>                    break;<br>                case EXIT_APPLICATION:<br>                    Looper.myLooper().quit();<br>                    break;<br>            }<br>        }<br>    }<br>}</pre><p><strong>Why this matters:</strong> Because every lifecycle event is just a message in a queue. If you do Thread.sleep(5000) in onCreate(), you have blocked the H handler. The system can&#39;t process the next message (like a <em>Stop</em> command or a <em>Touch</em> event), leading to the dreaded <strong>ANR (Application Not Responding)</strong>.</p><blockquote><strong>3. The Windowing Secret: PhoneWindow &amp; SurfaceFlinger</strong></blockquote><p>An Activity has no inherent ability to draw pixels. It is merely a controller. For a UI to appear, it must be attached to a <strong>Window</strong>.</p><ul><li><strong>PhoneWindow:</strong> When onCreate runs, the Activity creates a PhoneWindow (the only implementation of the Window class).</li><li><strong>DecorView:</strong> When you call setContentView(layout), you are actually telling PhoneWindow to inflate that XML and put it inside a DecorView.</li><li><strong>ViewRootImpl:</strong> This is the <em>glue</em>. During onResume(), the WindowManager creates a ViewRootImpl. This object is the one that actually communicates with the <strong>Choreographer</strong> and <strong>SurfaceFlinger</strong> to get pixels on the screen.</li></ul><blockquote><strong>4. The Zygote: Why Every App is a Clone</strong></blockquote><p>Android doesn’t start a JVM from scratch for every app launch — that would be too slow. Instead, it uses <strong>Zygote</strong>.</p><ul><li><strong>The Template:</strong> During boot, Zygote pre-loads thousands of standard Java/Android classes and resources into RAM.</li><li><strong>The Fork:</strong> When you launch an app, the System Server sends a socket command to Zygote to fork().</li><li><strong>Copy-on-Write (CoW):</strong> Your new app process shares the same physical RAM as Zygote. You only <em>own</em> the memory once you try to modify it.</li></ul><p><strong>Deep Detail:</strong> This is why static variables are so dangerous. If you aren’t careful with process death, you might assume a static variable initialized in Application.onCreate is still there, but if the OS kills your forked process and recreates it, that memory is wiped.</p><blockquote><strong>5. The State Bridge: Surviving Process Death</strong></blockquote><p>This is the #1 cause of <em>unreproducible</em> production crashes. There are two types of destruction:</p><ul><li><strong>Normal:</strong> You call finish() or the user hits <em>Back</em>.</li><li><strong>Abnormal (Process Death):</strong> The OS kills your app process to reclaim RAM for a high-priority task (like an incoming call).</li></ul><p>In <strong>Process Death</strong>, the system_server (which stays alive) saves a copy of your Bundle.</p><pre>// This Bundle travels across processes!<br>override fun onSaveInstanceState(outState: Bundle) {<br>    outState.putInt(&quot;user_id&quot;, currentUserId)<br>    super.onSaveInstanceState(outState)<br>}</pre><p>When the user returns, a <strong>new process</strong> is forked, and the system_server pushes that Bundle back across the Binder bridge into your onCreate(savedInstanceState: Bundle?).</p><p><strong>The Rule:</strong> If your code doesn’t account for savedInstanceState, it isn&#39;t <em>Android-Native</em>—it&#39;s just lucky.</p><blockquote><strong>6. Rendering: The 16.6ms Pressure Cooker</strong></blockquote><p>Android tries to render at <strong>60 frames per second</strong> (or 120Hz on modern displays). The <strong>Choreographer</strong> sends a VSYNC signal every <strong>16.6ms</strong>.</p><p>If your onStart() or onResume() logic looks like this:</p><pre>override fun onStart() {<br>    super.onStart()<br>    // Doing heavy work here...<br>    val data = repository.getHugeDataSync() <br>    updateUI(data)<br>}</pre><p>You are <em>occupying</em> the main thread when the VSYNC signal arrives. The Choreographer is forced to skip that frame. The user sees a <em>jank</em> or stutter.</p><blockquote><strong>7. The Back Stack: Navigation at the OS Level</strong></blockquote><p>Activities live in <strong>Tasks</strong>. A Task is a stack managed by the system, not your app.</p><p>When you use flags like FLAG_ACTIVITY_NEW_TASK or launch modes like singleTask, you are manipulating system-level behavior. Misunderstanding this leads to duplicate screens and broken deep-link navigation.</p><p><strong>Engineer’s Rule:</strong> Design your navigation to be predictable. If you can’t draw your Task stack on a whiteboard, your users will likely get lost in your app.</p><p><strong>The Mental Model for the Senior Engineer:</strong></p><p>To master the Activity, you must view it through these three lenses:</p><ul><li><strong>The Priority Lens:</strong> Is my Activity RESUMED? If not, the OS sees my process as a<em> low-priority cache</em> that can be killed at any moment.</li><li><strong>The IPC Lens:</strong> Every lifecycle method is a command from a remote process (system_server). I must acknowledge it quickly and keep the main thread free.</li><li><strong>The Stateless Lens:</strong> The Activity is temporary. The data belongs in a Repository or ViewModel; the state belongs in a Bundle.</li></ul><p><strong>Final Summary Table for the Pro Engineer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Sif1B5dHTTEi-CIR1Qg1A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd14b37fbda2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master ViewModel Once — Answer Every Android Interview Question]]></title>
            <link>https://medium.com/@jayshritotewad/master-viewmodel-once-answer-every-android-interview-question-b776d1a52000?source=rss-a8ebd69e078a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b776d1a52000</guid>
            <category><![CDATA[ui-state]]></category>
            <category><![CDATA[android-interviews]]></category>
            <category><![CDATA[android-developers]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Android App Developer]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 10:35:55 GMT</pubDate>
            <atom:updated>2026-02-02T10:35:55.593Z</atom:updated>
            <content:encoded><![CDATA[<h3>Master ViewModel Once — Answer Every Android Interview Question</h3><p><em>A practical, interview-oriented guide to understanding ViewModel in Android and why it exists.</em></p><h4>Before ViewModel: What Android Developers Used Instead</h4><p>Android had no official solution for managing UI state across configuration changes. Developers relied on a mix of patterns and workarounds.</p><ul><li><strong>Activities / Fragments as state holders</strong><br> UI state lived directly in lifecycle-bound components and was lost on configuration changes.</li><li><strong>onSaveInstanceState()</strong><br> Saved small, primitive UI data; quickly became messy for real screens.</li><li><strong>Retained Fragments</strong><br> Headless fragments used to survive configuration changes — powerful but error-prone.</li><li><strong>MVP (Model–View–Presenter)</strong><br> Improved separation of concerns, but lifecycle and state management were still manual.</li><li><strong>AsyncTask / Loaders</strong><br> Handled background work with complex and fragile lifecycle handling.</li><li><strong>Singletons / static objects</strong><br> Common but dangerous hacks that often caused memory leaks.</li></ul><h4>ViewModel: The Solution Android Needed</h4><p>ViewModel is a lifecycle-aware class that holds UI-related state and survives configuration changes, keeping Activities and Fragments free from business logic.</p><ul><li><strong>UI state lost on configuration changes</strong><br> ViewModel survives rotations and keeps state outside the Activity lifecycle.</li><li><strong>Bloated Activities and Fragments</strong><br> UI logic and state move out of UI controllers.</li><li><strong>Repeated API calls on screen rotation</strong><br> Data lives in ViewModel, not in onCreate().</li><li><strong>Manual lifecycle management</strong><br> ViewModel is lifecycle-aware and cleared automatically when its scope ends.</li><li><strong>Memory leaks caused by long-running tasks</strong><br> ViewModel avoids holding view references and cleans up safely.</li><li><strong>Hard-to-test UI logic</strong><br> ViewModel is a plain class and can be unit tested easily.</li></ul><h4>How ViewModel Survives Configuration Changes</h4><p>ViewModel does not magically survive configuration changes. It survives because it is built on top of Android’s <strong>non-configuration instance mechanism</strong>.</p><p>Let’s break this down using the most common example: <strong>screen rotation</strong>.</p><p>Step 1: Activity and ViewModel Are Created</p><p>When the screen is first created:</p><ul><li>The Activity is instantiated</li><li>A ViewModel is requested using ViewModelProvider</li><li>The ViewModel instance is stored inside a <strong>ViewModelStore</strong></li><li>The ViewModelStore is associated with the Activity’s <strong>non-configuration state</strong>, not with a specific Activity instance</li></ul><p>At this point, the ViewModel lives <strong>outside the Activity lifecycle</strong>.</p><p>Step 2: User Rotates the Device</p><p>When the device is rotated:</p><ul><li>Android detects a configuration change</li><li>The current Activity instance must be destroyed</li><li>Android begins tearing down the Activity</li></ul><p>Step 3: Android Checks Why the Activity Is Being Destroyed</p><p>Before destroying the Activity, Android checks whether this destruction is caused by a configuration change.</p><p>Internally, this is determined using:isChangingConfiguration()</p><ul><li>For rotation → returns <strong>true</strong></li><li>For a real finish (finish() / back press) → returns <strong>false</strong></li></ul><p>Step 4: Non-Configuration Objects Are Retained</p><p>Because the Activity is changing configurations:</p><ul><li>Android retains non-configuration instances</li><li>The <strong>ViewModelStore</strong> is saved as a non-configuration object</li><li>The Activity instance itself is destroyed</li></ul><p>The UI goes away, but the ViewModelStore does not.</p><p>Step 5: A New Activity Instance Is Created</p><p>After rotation:</p><ul><li>A new Activity instance is created</li><li>Android reattaches the retained non-configuration objects</li><li>ViewModelProvider looks inside the ViewModelStore</li><li>An existing ViewModel is found</li><li>The <strong>same ViewModel instance is returned</strong> (state preserved)</li></ul><h4>When Does ViewModel Get Cleared Then?</h4><p>ViewModel is <strong>not permanent</strong>. It is cleared when the scope that owns it is <strong>permanently destroyed</strong>.</p><p>When the Activity is destroyed <strong>without</strong> a configuration change:</p><ul><li>isChangingConfigurations() returns <strong>false</strong></li><li>Android does not retain non-configuration instances</li><li>The ViewModelStore is cleared</li><li>All ViewModels inside it are destroyed</li></ul><p>At this point, onCleared() is called on the ViewModel.</p><h4>What Should Be Done in onCleared()</h4><p>onCleared() is the final lifecycle callback of ViewModel.</p><p>It should be used to:</p><ul><li>Cancel coroutines</li><li>Clear resources</li><li>Stop background work</li><li>Release references</li></ul><p>This guarantees a clean shutdown without memory leaks.</p><h4>Process Death and ViewModel</h4><p>Process death occurs when the Android system kills the entire app process <strong>without delivering lifecycle callbacks</strong> to reclaim resources (low memory, long background time, force stop, OS prioritization).</p><p>Unlike configuration changes:</p><ul><li>The app is completely removed from memory</li><li>All in-memory objects are destroyed</li><li>The system may later recreate the app as if freshly launched</li></ul><p>When process death happens:</p><ul><li>ViewModel does <strong>not</strong> survive</li><li>The entire ViewModelStore is destroyed</li><li>All ViewModel instances are lost</li><li>onCleared() is <strong>not guaranteed</strong> to be called</li></ul><p>ViewModel only manages <strong>in-memory state</strong> and cannot protect against process termination.</p><h4>How ViewModel Handles Process Death with SavedStateHandle</h4><p>Although ViewModel itself cannot survive process death, it can be <strong>recreated with restored state</strong>.</p><p>Android enables this through <strong>state restoration</strong>, where small UI state is saved before the process is killed and restored when the app is recreated.</p><p><strong>Process Death and State Restoration</strong></p><p>If the system decides to recreate the app:</p><ul><li>A new Activity instance is created</li><li>The previously saved Bundle is restored</li><li>SavedStateRegistry is restored <strong>before ViewModel creation</strong></li><li>A new ViewModel instance is created</li><li>SavedStateHandle is injected with restored values</li></ul><p>At this point:</p><ul><li>The ViewModel is <strong>new</strong></li><li>But the UI state can be rebuilt using restored data</li></ul><p>State is saved <strong>only if you explicitly put it into the handle</strong>.</p><pre>class UserViewModel(<br>    private val savedStateHandle: SavedStateHandle<br>) : ViewModel()</pre><p>Saving state:</p><pre>fun setUserId(userId: String) {<br>    savedStateHandle[&quot;user_id&quot;] = userId<br>}</pre><p>Restoring state:</p><pre>val userId: String? = savedStateHandle[&quot;user_id&quot;]</pre><p>Recommended pattern:</p><pre>class UserViewModel(<br>    private val savedStateHandle: SavedStateHandle<br>) : ViewModel() {<br>    val userId: StateFlow&lt;String?&gt; =<br>        savedStateHandle.getStateFlow(&quot;user_id&quot;, null)<br>    fun updateUserId(id: String) {<br>        savedStateHandle[&quot;user_id&quot;] = id<br>    }<br>}</pre><p>This works because <strong>SavedStateHandle is internally backed by the SavedStateRegistry</strong>, which integrates with onSaveInstanceState() and restores state <strong>before ViewModel recreation</strong>.</p><h4>What Is Guaranteed (and What Is Not)</h4><ul><li><strong>ViewModel survival →</strong> Not guaranteed</li><li><strong>SavedStateHandle restoration →</strong> Not guaranteed</li><li><strong>Lifecycle callbacks →</strong> Not guaranteed</li><li><strong>Persistent storage (DB / disk) →</strong> Most reliable</li></ul><p>If the system does not recreate the app, none of these mechanisms run.</p><h4>Final Takeaway</h4><p>ViewModel manages <strong>in-memory UI state</strong>. SavedStateHandle helps <strong>restore small UI state after process death</strong>. Only <strong>persisted data</strong> provides true reliability.</p><p>Understanding where each mechanism fits is what shows <strong>real Android lifecycle mastery</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b776d1a52000" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>