<?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 Bearaddictedgames on Medium]]></title>
        <description><![CDATA[Stories by Bearaddictedgames on Medium]]></description>
        <link>https://medium.com/@bearaddictedgames?source=rss-20efb6bce797------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1Zo1un7IUfv_IRTA</url>
            <title>Stories by Bearaddictedgames on Medium</title>
            <link>https://medium.com/@bearaddictedgames?source=rss-20efb6bce797------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 14:48:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bearaddictedgames/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[From Massive File Scanning to Extreme Performance: AC Automaton in Android Cleaner Apps]]></title>
            <link>https://medium.com/@bearaddictedgames/from-massive-file-scanning-to-extreme-performance-ac-automaton-in-android-cleaner-apps-a35f59b4c88e?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/a35f59b4c88e</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 01:35:46 GMT</pubDate>
            <atom:updated>2026-11-06T01:35:46.384Z</atom:updated>
            <content:encoded><![CDATA[<p>When developing an Android Cleaner App, we face a massive performance challenge: How to quickly identify junk files among tens of thousands of files?</p><h3>Background: The Performance Disaster of Brute-Force Matching</h3><p>Typically, we prepare an array of junk keywords, such as [cache, log, tmp, thumb, apk…]. The logic is simple: if a file name or path contains any of these keywords, it’s marked as junk.</p><p>But reality is harsh: there could be hundreds of keywords, and a user’s phone can easily have tens of thousands of files. If we use traditional brute-force matching (like nested for loops with contains, or complex Regex), we have to compare each file against hundreds of keywords. That means millions of string scans, resulting in high CPU usage, slow scanning speed, and rapid battery drain.</p><p>To break this bottleneck, we introduced a legendary multi-pattern matching algorithm into our engine: Aho-Corasick Automaton.</p><h3>Step 1: Building the Trie Tree</h3><p>The first step is to build our keywords into a Trie tree in memory.</p><p>Assume our keywords are [sheer, he, ee], the tree structure looks like this:</p><p>text</p><pre>(root)<br>         /      \<br>        s        h(h1) -&gt; e(e2)<br>        |<br>        h(h0)<br>        |<br>        e(e0)<br>        |<br>        e(e1)<br>        |<br>        r<br>      (root) -&gt; e(e3) -&gt; e(e4)</pre><h3>Step 2: The “Fail Pointer”</h3><p>The fail pointer is the soul of this algorithm. A fail pointer points to a node (excluding the current path) where the string from the root to that node is the longest suffix of the current node’s string.</p><p>In actual calculation, we use the Parent Node Positioning Method:</p><ol><li>All direct children of the root have their fail pointers pointing to the root.</li><li>For other nodes, we look at its parent’s fail pointer. If that pointed node has a child with the same character as the current node, that child is the fail pointer. If not, we keep backtracking up the fail pointers until we reach the root.</li><li>If we reach the root and still find nothing, the fail pointer points to the root (or points to the child of the root if it matches).</li></ol><p>Based on this rule, we derive the fail pointers for the tree above:</p><ul><li>Level 1: s, h1, e3 -&gt; point to root.</li><li>Level 2: h0’s parent s points to root. Root has h1, so h0 -&gt; h1. e2’s parent h1 points to root. Root has e3, so e2 -&gt; e3. e4’s parent e3 points to root. No match, so e4 -&gt; root.</li><li>Level 3: e0’s parent h0 points to h1. h1 has e2, so e0 -&gt; e2.</li><li>Level 4: e1’s parent e0 points to e2. e2 doesn’t have e3. Backtrack: e2 points to e3. e3has e4, so e1 -&gt; e4. r’s parent e1 points to e4. No match, so r -&gt; root.</li></ul><h3>Step 3: Text Scanning (In Action)</h3><p>Once the tree and fail pointers are ready, we scan the file name.</p><p>Matching Principles: Starting from the first character of the string, go down the tree.</p><ol><li>Jump on Mismatch: If a character doesn’t match, immediately follow the fail pointer to switch paths. The text pointer NEVER goes backward.</li><li>Check the Chain on Match: Whenever a character matches successfully, we don’t just check if the current node is a leaf. We must follow the fail pointer chain upward (all the way to the root) to check if any node on this chain marks the end of a keyword. If yes, it’s a hit!</li></ol><p>Example: Text string: hoostcache Keywords: [hoot, ostcac, cache].</p><ol><li>Read h, o, o: Go down to h -&gt; o -&gt; o.</li><li>Read s: No s under h-&gt;o-&gt;o. Mismatch!</li><li>Read t, c, a, c: Go down to o -&gt; s -&gt; t -&gt; c -&gt; a -&gt; c.</li></ol><h3>Summary</h3><p>By introducing the AC Automaton, we completely eliminated the performance disaster of Regex. Whether the keyword array has 100 or 10,000 words, the matching time complexity is always O(L) (where L is the length of the file name). This is the core secret that enables our cleaning engine to scan tens of thousands of files in seconds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a35f59b4c88e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Reliable and High-Performance IM Architecture: From Message Consistency to Jetpack…]]></title>
            <link>https://medium.com/@bearaddictedgames/designing-a-reliable-and-high-performance-im-architecture-from-message-consistency-to-jetpack-116368df1240?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/116368df1240</guid>
            <category><![CDATA[instant-messaging]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 06:32:22 GMT</pubDate>
            <atom:updated>2026-11-05T06:32:22.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing a Reliable and High-Performance IM Architecture: From Message Consistency to Jetpack Compose Optimization</h3><p>When developing an Instant Messaging (IM) app, developers face three ultimate challenges:</p><p>• Reliability: How to ensure messages are never lost or duplicated?</p><p>• Consistency: How to guarantee message ordering without UI jitter?</p><p>• Performance: How to maintain a butter-smooth 60fps experience with massively long lists?</p><p>This article dives deep into the architecture of a real-world Android chat application, exploring how we elegantly solved these three problems through precise event-driven design and UI optimization.</p><p>1. Message Layer: Highly Reliable Communication</p><p>The core of the message layer is achieving Eventual Consistency and Concurrency Safety. We use OkHttp WebSocket as our channel, building a strict reporting and sorting mechanism on top of it.</p><p>1.1 Communication Base &amp; Concurrency Control</p><p>• Orderly Delivery: WebSocket is essentially a persistent HTTP channel. Thanks to OkHttp’s single-threaded send queue management, send operations are guaranteed to be written to the connection in order.</p><p>• Thread Safety Isolation: In our MessagesManager (a process singleton created via Dagger), we maintain a dedicated read/write thread bound to a Looper. Both user-triggered sends from the main thread and OkHttp ACK callbacks from network threads are dispatched to this queue. This serialization completely eliminates concurrency hazards when accessing the outBox or the database.</p><p>1.2 Core Mechanism: OutBox &amp; Dual-Track Seq Strategy</p><p>The key to ensuring reliability and preventing UI jitter lies in how we handle sequence numbers (Seq):</p><p>• Authoritative Seq: The server assigns a monotonically increasing serverSeq for each message within a conversation and returns it in the ACK.</p><p>• Client OutBox: We generate a globally unique msgId (UUID + timestamp), write it to the DB, append it to the outBox queue, and finally call send().</p><p>• Dual-Track Seq Strategy:</p><ul><li>Received messages: sortSeq equals serverSeq.</li><li>Sent messages (Pending ACK): serverSeq is null. sortSeq temporarily inherits the serverSeq of the previous message (or 0 if it’s the first).</li><li>Upon ACK: sortSeq is updated to the actual serverSeq, cascading updates to subsequent unconfirmed messages from the sender.</li></ul><p>1.3 Exception Handling &amp; Reconnection Recovery</p><p>Robust exception handling is what keeps an IM app alive on volatile mobile networks:</p><p>• Full Send Queue: If send() returns false, it means the WebSocket buffer is full. Instead of silently dropping, we mark the message in the outBox as Failed.</p><p>• Heartbeat &amp; Polling: We use OkHttp’s pingInterval for heartbeats. Concurrently, a 5-second periodic clock polls the outBox. Messages with ACK timeouts, as well as Failed ones, are retried via send() (since ACKs can be lost).</p><p>• Network Monitoring: We listen to system connectivity changes, applying exponential backoff for reconnection attempts when offline, and reconnecting immediately upon network restoration.</p><p>• Cold Start &amp; Background Wakeup: On app restart, any message with a null serverSeq is reloaded into the outBox and retried. If the app is killed, push notifications wake the client; upon connection, the server re-delivers any unacknowledged messages in order.</p><p>• Media Messages: For images/audio, we pipeline: Save to DB -&gt; Upload File -&gt; Append to OutBox -&gt; Send. This prevents large files from blocking the text channel.</p><p>1.4 Conversation Management</p><p>A process singleton ConversationManager listens to Room DB invalidations, automatically maintaining the conversation list, latest message previews, and unread counts.</p><p>2. UI Layer: Intention-Aware Sliding Window &amp; Jetpack Compose Tuning</p><p>The UI layer aims for Zero Jitter and Extreme Smoothness. We implemented rigorous controls in data loading and view rendering.</p><p>2.1 Eliminating Race Conditions on Initialization</p><p>MessagesManager exposes a Flow&lt;Message&gt;. In the ViewModel, we subscribe to the new message flow FIRST, then trigger historical data loading. This prevents missing real-time messages arriving during the DB query window. After loading, messages are deduplicated by msgId on the main thread.</p><p>2.2 Zero Jitter: Stable Keys and the Intention-Aware Sliding Window</p><p>Infinite list growth leads to OOM; re-sorting upon ACK receipt may causes UI jumps. Our solution:</p><p>• Memory Limits: The in-memory list is capped (e.g., 500 messages). We combine this with LazyListState to track user behavior.</p><p>• Intention Detection: We determine if the user is “Browsing History” (scrolled up) or “Chatting” (near the bottom).</p><p>• Dynamic Eviction:</p><ul><li>Chatting Mode: New messages append to the bottom; old messages are evicted from the top.</li><li>Browsing Mode: New messages are saved to the DB but not inserted into the list. Newer in-memory messages are evicted from the bottom to preserve the current viewport.</li></ul><p>• Visual Anchoring: By supplying the unique msgId as the key in LazyColumn, Compose automatically matches items and recalculates offsets when the underlying list is trimmed. This results in visually imperceptible list mutations.</p><p>2.3 Jetpack Compose Performance &amp; Recomposition Tuning</p><p>We applied a series of surgical optimizations:</p><p>• Downgrading &amp; Throttling: Composables read only the minimal state they need. derivedStateOf throttles high-frequency updates.</p><p>• On-Demand Loading:</p><ul><li>Pause Coil image loading during scrolling by setting model = null; resume when scrolling stops.</li><li>Check viewport visibility to cancel image requests for items far off-screen.</li><li>Pass size constraints to Coil to decode only the required dimensions.</li></ul><p>• Minimizing Recomposition:</p><ul><li>Keep all logic in the ViewModel; no heavy lifting inside list items.</li><li>Wrap event callbacks with remember to prevent Lambda recreation and cascading recompositions.</li><li>Provide stable contentType to aid Compose’s component reuse.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=116368df1240" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Android Storage Architecture: From Physical Partitions to App-Level Access]]></title>
            <link>https://medium.com/@bearaddictedgames/deep-dive-into-android-storage-architecture-from-physical-partitions-to-app-level-access-aef0cff89f75?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/aef0cff89f75</guid>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 02:16:18 GMT</pubDate>
            <atom:updated>2026-11-05T02:16:18.105Z</atom:updated>
            <content:encoded><![CDATA[<p>In Android development, especially when building apps involving file management, cleaner tools, or media processing, a deep understanding of the disk space and file system architecture is crucial. This article will break down the architecture from physical partitions at the bottom, up through mount paths, app-level storage tiers, and finally to MediaStore and SAF in modern Android.</p><h3>1. Physical Partitions: The Cornerstone of Storage</h3><p>From a low-level physical perspective, the disk space of an Android device is typically divided into several core partitions:</p><ul><li>/system: Stores the core files of the Android OS. It is mounted as read-only and cannot be written to.</li><li>/vendor: The area where device manufacturers (OEMs) store HAL (Hardware Abstraction Layer) code and proprietary drivers.</li><li>/cache: The cache area for the system and some apps. Regular apps generally do not access it directly.</li><li>/data: The core storage area for user data. This is the actual location where all app private data and user files are stored. Without Root access, regular apps cannot directly read/write the underlying partition. Therefore, the system provides a series of mount paths and APIs for restricted and secure access.</li></ul><h3>2. Mount Paths: Different Paths to the Same Destination</h3><p>To maintain compatibility with older systems and implement multi-user and permission tiers, developers encounter various external storage paths. In reality, they all eventually point to the same physical entity: /sdcard ➡️ /storage/self/primary ➡️ /storage/emulated/0 ➡️ /data/media/0</p><p>Among these, /data/media/0 is the actual physical path of user files on the flash memory, but it is isolated from regular apps. Apps must access it indirectly through the preceding multi-layer symbolic links and mount points. The system uses intermediate layers to achieve path compatibility while enforcing strict permission interception.</p><h3>3. App-Level Tiers: Internal Storage vs. External Storage</h3><p>Although the underlying physical space is shared, Android abstracts the concepts of “Internal Storage” and “External Storage” for apps to facilitate permission management.</p><p>1. Internal Storage</p><ul><li>Access: Obtained via context.filesDir, located under /data/data/&lt;package_name&gt;/. context.cacheDir points to the cache directory at the same level.</li><li>Features: Absolutely private; inaccessible to other apps; requires no runtime permissions; completely removed upon app uninstallation.</li></ul><p>2. External App-Specific Storage</p><ul><li>Access: Obtained via context.getExternalFilesDir(), located at /storage/emulated/0/Android/data/&lt;package_name&gt;/files/. Similarly, getExternalCacheDir() is available.</li><li>Features: Requires no permissions; inaccessible to other apps; removed upon app uninstallation.</li></ul><p>Core Differences Between Internal Storage and External App-Specific Storage:</p><ol><li>External Visibility: When connected to a PC via USB, the external app-specific storage is visible, while internal storage is not.</li><li>Auto Backup: Internal storage participates in the system’s Auto Backup mechanism by default, while external app-specific storage does not.</li><li>I/O Performance: Internal storage is directly managed by the kernel and is the fastest. The external app-specific storage is wrapped by FUSE (Filesystem in Userspace), incurring overhead from context switching between user mode and kernel mode during I/O operations, resulting in relatively slower read/write speeds.</li></ol><p>Best Practices: Internal storage is suitable for lightweight and sensitive data (like databases, configs); external app-specific storage is more suitable for large media files (like offline videos, large images).</p><p>3. Public Shared Storage</p><ul><li>Access: Obtained via Environment.getExternalStorageDirectory(), which is /storage/emulated/0/.</li><li>Features: Extremely high permission requirements. Under the Scoped Storage mechanism in Android 11+, apps cannot access it arbitrarily.</li></ul><h3>4. Breaking the Sandbox: MediaStore and SAF</h3><p>To allow apps to access public space while protecting user privacy, modern Android primarily relies on two mechanisms:</p><p>1. MediaStore: The System-Level Media Index Database MediaStore is essentially a database for multimedia files (images, videos, audio), storing the metadata of media files in public shared storage. Apps access it via ContentResolver.</p><ul><li>Permission Mechanism: Starting from Android 13, reading media files requires fine-grained permissions (READ_MEDIA_IMAGES, READ_MEDIA_VIDEO, READ_MEDIA_AUDIO), which are much easier to obtain than the global MANAGE_EXTERNAL_STORAGE. Writing media files created by the app itself requires no permissions; only when modifying or deleting files created by other apps does it require user authorization via a system pop-up on a per-instance basis.</li></ul><p>2. SAF (Storage Access Framework): Directory Tree Access via User Grant MediaStore only covers media files. For non-media files (like documents, specific app cache directories), SAF must be used.</p><ul><li>Authorization Mechanism: SAF bypasses traditional Manifest permission declarations. Its permission comes entirely from the user’s explicit choice.</li><li>Workflow: The app launches the system’s DocumentsUI via Intent.ACTION_OPEN_DOCUMENT_TREE, letting the user select a specific directory. After obtaining the content:// URI representing that directory, the app calls ContentResolver.takePersistableUriPermission() to persist the grant, making it valid even after device reboots.</li><li>Operational Constraints: A crucial rule is that after obtaining the persisted URI, it cannot be converted back to a raw file path. The app must use the DocumentFile or ContentResolver API to enumerate and operate on the files within.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aef0cff89f75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the Hood: The 15-Step Journey of an App’s first Android UI Frame]]></title>
            <link>https://medium.com/@bearaddictedgames/under-the-hood-the-15-step-journey-of-an-apps-first-android-ui-frame-225d04d4a07f?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/225d04d4a07f</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 08:01:34 GMT</pubDate>
            <atom:updated>2026-10-28T08:01:34.130Z</atom:updated>
            <content:encoded><![CDATA[<p>What truly happens from the moment an Activity is instantiated to the exact moment pixels light up the screen?</p><p>Here is the microscopic physical blueprint of the Android UI Rendering Pipeline, breaking down the perfect choreography of the Control Plane, Data Plane, and State Machine.</p><p>1. Triggering the Launch, AMS (ActivityManagerService) sends a Binder transaction to the App process, invoking ApplicationThread.scheduleLaunchActivity with the ActivityClientRecord (a data package containing the target Activity’s class name, e.g., com.example.MainActivity).</p><p>2. Thread Handoff, The App’s Binder thread receives the message and immediately posts it via a Handler to the main thread.</p><p>3. Reflection &amp; Creation, ActivityThread instantiates the Activity via Reflection.</p><p>4. Activity Management, ActivityThread maintains a Map (specifically mActivities) to track all live Activity instances within the current process.</p><p>5. Window Binding, Activity.attach() is invoked, inside which a PhoneWindow is created and tightly bound to the Activity.</p><p>6. Building the View Tree, During onCreate, setContentView is called. The Activity delegates to PhoneWindow, which creates the DecorView. LayoutInflater then parses R.layout.xxx into a View tree and mounts it into android.R.id.content (the FrameLayout inside DecorView).</p><p>7. Preparing the Canvas &amp; The Trigger Mechanism, After onResume, WindowManager.addView(mDecorView) is called. Internally, this request is delegated to WindowManagerGlobal, a process-wide singleton. It creates the ViewRootImpl and strongly references it in its internal mRoots list to manage the window’s lifecycle. ViewRootImpl contains two core members: mView (pointing to DecorView) and mWindowSession (the Binder proxy to WMS).</p><p>Note here, when a View needs to trigger a redraw via View.invalidate(), it does not communicate with WMS directly. During the view tree attachment phase (dispatchAttachedToWindow), ViewRootImpl creates a View.AttachInfo object (which holds a strong reference to the ViewRootImpl) and injects it into every View in the hierarchy. When invalidate() is called, the View retrieves its mAttachInfo and invokes mAttachInfo.mViewRootImpl.invalidateChild(), bubbling the request back to the root.</p><p>8. Canvas Allocation, ViewRootImpl.setView() is called. It makes a synchronous cross-process request to WMS via mWindowSession.addToDisplay(). WMS coordinates with SurfaceFlinger to create a Layer and a BufferQueue, returning a SurfaceControl handle. ViewRootImpl uses this to create the Surface and acquires the Producer handle of the BufferQueue.</p><p>9. Scheduling the Draw, ViewRootImpl calls requestLayout(), inserting a Sync Barrier into the main thread’s MessageQueue, and posts a CALLBACK_TRAVERSAL to the Choreographer.</p><p>10. VSYNC &amp; Wakeup, When the hardware VSYNC signal arrives, Choreographer posts an asynchronous message. The Looper bypasses the Sync Barrier, takes the message, and executes ViewRootImpl.performTraversals().</p><p>11. Measure, Layout, Draw</p><ul><li>Measure: Recursively calculates the required size of each View from DecorView downwards.</li><li>Layout: Positions the sized Views at specified coordinates relative to the Surface.</li><li>Draw: With hardware acceleration enabled, it doesn’t draw pixels directly. Instead, it records all draw commands into a DisplayList instruction tree.</li></ul><p>12. Thread Offloading, The main thread syncs the DisplayList to the RenderThread via SyncQueue. The handoff is complete, and the main thread immediately resumes processing the next user input event. It never waits for the GPU.</p><p>13. GPU Translation, RenderThread translates the DisplayList into low-level OpenGL / Vulkan commands.</p><p>14. Asynchronous Rendering, RenderThread requests a GraphicBuffer from the Surface queue, submits the commands to the GPU, and immediately enqueues the GraphicBuffer back to the queue (marking it as QUEUED) with a locked Fence.</p><p>15. Composition &amp; Display, When the next VSYNC arrives, SurfaceFlinger traverses the queues and checks the Fence signal(ensuring the GPU has finished rendering). Once unlocked, it acquires the buffer (marking it ACQUIRED), updates the Layers, and passes them to the HWC (Hardware Composer) for final rendering and display.</p><p>💡 Architect’s Takeaway: This 15-step flow highlights the elegance of Android’s architecture: Control/Data Plane separation, asynchronous rendering, and Fence-driven state machines. By offloading GPU rendering to the RenderThread and leveraging a multi-buffered queue, Android eliminates main-thread blocking and achieves zero-copy, tear-free rendering.</p><p><em>(Note: For a deeper dive into the physical mechanics of Steps 13–15 — including the four-state lifecycle of a GraphicBuffer [FREE -&gt; DEQUEUED -&gt; QUEUED -&gt; ACQUIRED] and the role of Gralloc — please refer to my previous article here: </em><a href="https://medium.com/@bearaddictedgames/decoding-the-android-graphics-pipeline-from-window-creation-to-hwc-composition-14be625756a6?sharedUserId=bearaddictedgames">https://medium.com/@bearaddictedgames/decoding-the-android-graphics-pipeline-from-window-creation-to-hwc-composition-14be625756a6?sharedUserId=bearaddictedgames</a><em>)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=225d04d4a07f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding the Android Graphics Pipeline: From Window Creation to HWC Composition]]></title>
            <link>https://medium.com/@bearaddictedgames/decoding-the-android-graphics-pipeline-from-window-creation-to-hwc-composition-14be625756a6?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/14be625756a6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[surface]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 07:57:08 GMT</pubDate>
            <atom:updated>2026-10-28T07:57:08.234Z</atom:updated>
            <content:encoded><![CDATA[<p>When diving deep into Android’s graphics system, it’s easy to get lost in fragmented concepts. Today, let’s unveil the complete physical flow from when an App requests a new window to the exact moment pixels light up on the screen.</p><p>1. Control Plane: Window Genesis &amp; Canvas Allocation When an App needs a new window, it sends parameters (size, alpha, flags, etc.) to WMS. After validation, WMS instructs SurfaceFlinger via Binder to create a Layer in memory, which holds spatial attributes (Z-order, display size, alpha). Simultaneously, SurfaceFlinger creates a Producer-Consumer queue (BufferQueue) and generates a control handle for the layer: SurfaceControl. This handle is passed back to the App’s ViewRootImpl, which instantiates a Surface and requests the Producer handle of the BufferQueue from SurfaceFlinger.</p><p>2. Data Plane: Asynchronous Rendering &amp; Fence Synchronization When RenderThread receives the DisplayList from the main thread, it translates it into executable OpenGL commands. It then checks the Surface for an available GraphicBuffer. If none exists, it requests GPU-friendly physical memory from the kernel via Gralloc, marking the buffer’s state as DEQUEUED. Crucially, after submitting commands to the GPU, the CPU does not wait synchronously. It immediately enqueues the buffer, marking it as QUEUED. Since the GPU is still rendering in the background, the buffer’s attached Fence signal remains locked (off); it only unlocks once the GPU finishes.</p><p>3. Composition Plane: VSYNC-Driven Cycle When the hardware VSYNC signal arrives, SurfaceFlinger iterates through all BufferQueues. It inspects the head of the queue: if the Fence is unlocked (rendering complete), it acquires the buffer, marking it as ACQUIRED. SurfaceFlinger then iterates through all Layers, filling in the new buffers (layers without new frames reuse the previous frame’s buffer), and passes them to the Hardware Composer (HWC) for final composition and display. Once composition is done, the old buffer’s state resets to FREE, returning to the queue for reuse.</p><p>💡 Architect’s Takeaway: This architecture — Control/Data Plane separation paired with a Multi-buffering State Machine &amp; asynchronous Fence sync — achieves zero-copy cross-process transmission. It eliminates main-thread blocking and completely eradicates screen tearing. This is the ultimate bedrock enabling Android’s buttery-smooth 120Hz rendering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14be625756a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive: The 6-Step Physical Process of Android Binder Communication]]></title>
            <link>https://medium.com/@bearaddictedgames/deep-dive-the-6-step-physical-process-of-android-binder-communication-dd40db7eb250?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd40db7eb250</guid>
            <category><![CDATA[binders]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[system-architecture]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 03:40:14 GMT</pubDate>
            <atom:updated>2026-10-26T03:40:14.770Z</atom:updated>
            <content:encoded><![CDATA[<p>In the Android ecosystem, Binder is the absolute soul of Inter-Process Communication (IPC). Most developers know it follows a Client-Server (C/S) architecture and is faster than traditional Sockets. But have you ever wondered about the physical memory layout and the Kernel/User space transitions happening under the hood?</p><p>Let’s bypass the complex C++ source code and dissect the entire Binder communication process from the perspective of physical memory and OS scheduling, broken down into 6 steps.</p><p>📌 Prerequisite: The “1MB Shared Memory” Misconception Before diving into the flow, we must correct a common misunderstanding: The ~1MB mapped memory (Binder buffer) is NOT allocated on-demand during communication. Instead, it is allocated via the mmap system call into the Kernel Space and simultaneously mapped into the User Space of both the Client and Server processes the moment they start (during ProcessState initialization). Every process has exactly one such buffer.</p><p>🚀 The 6-Step Binder Communication Flow</p><p>Step 1: The Client Initiates the Request (Data Preparation) When the Client needs to call another process, it first packs the request data into a standard Parcel object within its own User Space. Then, it triggers an ioctl system call (using the svc instruction), causing the CPU privilege level to escalate from EL0 (User Mode) to EL1 (Kernel Mode), sending the request to the Binder driver. <em>(Note: At this point, the data is in the Client’s regular User Space, not yet in the shared memory).</em></p><p>Step 2: The “One-Copy” Magic (Client -&gt; Server) Once the Binder driver takes over and identifies the target Server process, it performs the magic: it copies the data exactly ONCE from the Client’s User Space directly into the ~1MB Kernel buffer allocated for the Server process (which is already mapped into the Server’s User Space). <em>(Note: Traditional Sockets require two copies: User A -&gt; Kernel -&gt; User B. Binder eliminates one).</em></p><p>Step 3: Task Enqueue and Thread Wake-up After the copy, the Binder driver generates a task node (binder_work) in the Kernel and appends it to the Server’s dedicated todo queue. Then, the driver wakes up an idle Binder thread from the Server’s Binder thread pool (typically 16 threads).</p><p>Step 4: Server Executes the Task (Returning to User Space) The awakened Server Binder thread is still in Kernel Mode. It fetches the task from the todo queue, carries the data, and executes the eret instruction to drop privileges back to EL0 (User Mode). It then executes the corresponding onTransact method (e.g., triggering AMS’s startActivity logic). Once done, the Server creates a new Parcel in its own User Space with the return values, and executes a system call to enter Kernel Mode again.</p><p>Step 5: The Reply Copy (Server -&gt; Client) The Binder driver receives the reply data and repeats the “one-copy” magic: it copies the data from the Server’s User Space directly into the 1MB shared memory buffer pre-mapped in the Client’s User Space.</p><p>Step 6: Wake Up the Client (Reading the Result) Finally, the Binder driver places the reply task into the Client’s todo queue and wakes up the sleeping Client thread. The Client wakes up and reads the result directly from its own mapped shared memory, concluding the IPC process.</p><p>💡 Architect’s Summary: Why is Binder Fast AND Secure?</p><p>Looking at these 6 steps, Binder’s symmetry becomes clear:</p><ul><li>Control Plane: Relies on the todo queue and Kernel thread pool wake-ups to handle high-concurrency task scheduling.</li><li>Data Plane: Relies on mmap memory mapping. Each direction (Request and Reply) requires only exactly ONE copy, achieving ultimate zero-copy performance for the receiver.</li></ul><p>You might wonder: Since we are already using memory mapping, why not map the EXACT SAME physical memory page for both Client and Server to achieve true “Zero-Copy”? The answer is Security. If they shared the exact same physical page, a malicious Client could directly modify the Server’s memory (e.g., the system’s AMS), crashing the OS. That single copy performed by the Kernel acts not just as a data transfer, but as a strict security boundary and permission check, perfectly balancing extreme performance with absolute isolation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd40db7eb250" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unraveling the Android Blueprint: The Physical Journey from Power-On to App Execution]]></title>
            <link>https://medium.com/@bearaddictedgames/unraveling-the-android-blueprint-the-physical-journey-from-power-on-to-app-execution-2b2aac4e632c?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2aac4e632c</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[android-internals]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[arm]]></category>
            <category><![CDATA[system-architecture]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 04:22:48 GMT</pubDate>
            <atom:updated>2026-10-25T04:22:48.385Z</atom:updated>
            <content:encoded><![CDATA[<p>To truly master Android architecture, we must look beyond the APIs and understand the hardware. Here is the microscopic physical blueprint of how an Android device actually works, from the moment you press the power button to your App running on the screen:</p><p>1. The Essence: An Ocean of Instructions, Whether it’s the massive Android OS or the App you just wrote, everything is fundamentally just a set of instructions sitting in RAM. The ARM CPU (SoC) can only execute extremely basic physical actions: jump instructions, read from a memory address, write to a register, or perform basic arithmetic. The entire Android software ecosystem is simply a giant permutation and combination of these basic assembly instructions.</p><p>2. The Boot Relay: From Hardwired Logic to a Giant OS, The moment you press the power button, only the primary ARM core wakes up (others remain asleep). The hardware circuitry forces it to read a piece of code hardcoded inside the SoC (BootROM). This code loads the BootLoader from the phone’s flash storage (UFS) into RAM. The BootLoader then takes on the heavy lifting: it loads the massive Android Linux Kernel image (boot.img) into RAM, jumps to the kernel’s entry point, and officially hands over CPU control to the Linux kernel. (The kernel then spawns the init process, which incubates Zygote, eventually bringing your App to life).</p><p>3. The Memory Sandbox: Multi-level Page Tables &amp; On-Demand Paging, For isolation and security, the OS maintains page tables. They map virtual addresses to physical memory pages and dictate access permissions (read/write/execute, privilege level). If an App attempts to access kernel memory, the MMU (Memory Management Unit) hardware intercepts it immediately, causing a segmentation fault. Because virtual memory is massive, Android uses multi-level page tables with dynamic on-demand allocation. Only when you access a specific virtual address and trigger a page fault does the kernel step in, allocate the page table entries, bind them to actual physical memory, and mark them as valid.</p><p>4. Idle &amp; Interrupts: Sleep and Wake-up, Once the Linux kernel finishes initialization, it maintains an interrupt vector table. If there is no work to do, it executes the WFI (Wait For Interrupt) instruction, putting the CPU into a deep low-power sleep state. Interrupts are divided into hardware interrupts (screen touches, network data) and software interrupts. When a signal arrives, the CPU evaluates its priority. The hardware automatically saves the execution context (pushing registers onto the kernel stack), consults the interrupt vector table, and jumps to the kernel’s corresponding driver/handler code. Once finished, it restores the context and resumes previous work.</p><p>5. Privilege Escalation: System Calls &amp; Hardware Compliance, ARM CPUs maintain Exception Levels (EL0 to EL3). Your App runs at the lowest level, EL0, and is physically restricted from directly accessing hardware or high-privilege memory. When an App needs to send network packets, read files, or perform Binder IPC, it must make a System Call.</p><p>The App writes parameters to CPU registers and executes an svc (Supervisor Call) soft interrupt instruction. Upon execution, the hardware instantly escalates the privilege level to EL1 (Kernel Mode), automatically pushes the current register context (like the PC pointer) onto the kernel stack, and jumps to the corresponding system call handler via the vector table. The kernel performs strict security checks, executes the request (e.g., Binder driver dispatching), writes the result back, and drops the privilege level back to EL0, returning control to the App.</p><p>Understanding this hardware-to-software physical blueprint is the ultimate moat for an Android architect. It shifts your debugging mindset from “why is my Java code crashing?” to “which physical layer of the CPU, OS, or framework is failing?”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2aac4e632c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying the Android DEX File Format: A Deep Dive into Compilation and Class Loading ]]></title>
            <link>https://medium.com/@bearaddictedgames/demystifying-the-android-dex-file-format-a-deep-dive-into-compilation-and-class-loading-be365d7fb485?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/be365d7fb485</guid>
            <category><![CDATA[class-loader]]></category>
            <category><![CDATA[mmap]]></category>
            <category><![CDATA[dex]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[d8]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 08:32:35 GMT</pubDate>
            <atom:updated>2026-10-24T08:32:35.713Z</atom:updated>
            <content:encoded><![CDATA[<p>The Kotlin compiler compiles each class into a .class file containing bytecode. Subsequently, the D8 compiler merges and compresses all these .class files into a single .dex file (or multiple files if the method count exceeds the 65,536 limit).</p><p>During compilation, D8 places a Header at the beginning of the file, recording the magic number (ensuring this is a valid dex file), file size, and checksum.</p><p>Then, all strings are extracted and placed into a large String IDs array. Actually, the String IDsarray only stores offsets; the real string contents are stored in the Data section. This includes class names, type descriptors, method names, method signatures, variable names, string constants, annotation strings, and paths.</p><p>Next, all types are extracted into the Type IDs array, which essentially contains indices pointing to the corresponding String IDs.</p><p>Following this is the Proto IDs array, which records all possible combinations of method input parameters and return types. For example:</p><p>text</p><pre>0A 00 00 00  // shorty_idx: 10 (points to StringIds[#10] &quot;LII&quot;)<br>02 00 00 00  // return_type_idx: 2 (points to TypeIds[#2] String)<br>00 08 00 00  // parameters_off: 0x0800 (offset pointing to TypeList)</pre><p>The TypeList is actually stored in the Data section. Note: The Shorty is a simplified representation of input parameters and return types, where all object types are represented by L. Therefore, it can only be used for initial filtering, not exact matching. The TypeList contains the specific input parameter types, physically stored in the Data section, with only an offset stored in the Proto IDs.</p><p>Field IDs (Field Index Area): Records all member variables.</p><p>java</p><pre>public class User {<br>    public String name;<br>    public int age;<br>}</pre><p>text</p><pre>// 1. First field: name (8 bytes)<br>05 00        // class_idx (2 bytes): points to TypeIds[#5] (User class)<br>0A 00        // type_idx  (2 bytes): points to TypeIds[#10] (String)<br>14 00 00 00  // name_idx  (4 bytes): points to StringIds[#20] (&quot;name&quot;)</pre><pre>// 2. Second field: age (8 bytes)<br>05 00        // class_idx (2 bytes): points to TypeIds[#5] (User class)<br>02 00        // type_idx  (2 bytes): points to TypeIds[#2] (int)<br>15 00 00 00  // name_idx  (4 bytes): points to StringIds[#21] (&quot;age&quot;)</pre><p>Method IDs (Method Index Area): Records all methods.</p><p>java</p><pre>public class Calculator {<br>    public int add(int a, int b) { return a + b; }<br>    public void log(String msg) { ... }<br>}</pre><p>text</p><pre>// 1. First method: add (8 bytes)<br>05 00        // class_idx (2 bytes): points to TypeIds[#5] (Calculator)<br>08 00        // proto_idx (2 bytes): points to ProtoIds[#8] (Int, Int) -&gt; Int<br>14 00 00 00  // name_idx  (4 bytes): points to StringIds[#20] (&quot;add&quot;)</pre><pre>// 2. Second method: log (8 bytes)<br>05 00        // class_idx (2 bytes): points to TypeIds[#5] (Calculator)<br>09 00        // proto_idx (2 bytes): points to ProtoIds[#9] (String) -&gt; void<br>15 00 00 00  // name_idx  (4 bytes): points to StringIds[#21] (&quot;log&quot;)</pre><p>Class Defs (Class Definition Area): This is the core! It links all scattered IDs together, telling the system: &quot;What is this class called, what does it inherit, what methods does it have, and where is the method code located.&quot;</p><p>java</p><pre>public class User extends Object {<br>    public int age;<br>    public void sayHi() { ... }<br>}</pre><p>text</p><pre>// 1. Basic Identity Info (16 bytes)<br>05 00 00 00  // class_idx (4 bytes): points to TypeIds[#5] -&gt; &quot;Lcom/example/User;&quot;<br>01 00 00 00  // access_flags (4 bytes): 0x01 indicates public<br>02 00 00 00  // superclass_idx (4 bytes): points to TypeIds[#2] -&gt; &quot;Ljava/lang/Object;&quot;<br>00 00 00 00  // interfaces_off (4 bytes): 0 (No interfaces)</pre><pre>// 2. Associated Info (16 bytes)<br>0A 00 00 00  // source_file_idx (4 bytes): points to StringIds[#10] -&gt; &quot;User.java&quot;<br>00 00 00 00  // annotations_off (4 bytes): 0 (No annotations)<br>00 08 00 00  // class_data_off (4 bytes): 0x0800 (🔥 Core: points to specific data in the Data section)<br>00 00 00 00  // static_values_off (4 bytes): 0 (No static initial values)</pre><p>Data Section: The place where actual code instructions (Dalvik bytecode) and constant values are truly stored.</p><p>When our code needs to load a class (prior to the introduction ofDexCache and hash table optimizations), the underlying mechanism relies on mmap (memory mapping + page faults) + binary search. Physically speaking, all String IDs are stored in sorted order in the DEX file, and the strings in the Data section are tightly packed in the same order. Thus, we can read the middle string first, compare for binary search until we find the target. During this process, multiple page faults will occur, loading the corresponding 4KB data pages on demand.</p><p>Once the string is found, we use the same logic to find the corresponding type in Type IDs, and then find the class definition in Class Defs. The class metadata is then loaded into the Method Area in memory. Only when a specific method is actually executed will the system jump to the Data section to load and execute the corresponding bytecode.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be365d7fb485" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Tour of How Resource XML Is Compiled into Binary]]></title>
            <link>https://medium.com/@bearaddictedgames/a-quick-tour-of-how-resource-xml-is-compiled-into-binary-242e540b3637?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/242e540b3637</guid>
            <category><![CDATA[r8]]></category>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[apk]]></category>
            <category><![CDATA[resource-optimization]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 01:32:49 GMT</pubDate>
            <atom:updated>2026-10-23T01:32:49.060Z</atom:updated>
            <content:encoded><![CDATA[<p>When delving deep into Android app performance optimization, APK size reduction, startup acceleration, and security hardening, these topics can be difficult to master. Many Android developers know that “XML is compiled into binary,” but what exactly happens under the hood? Why does it load so fast? And why can reverse-engineering tools easily steal your resources?</p><p>Today, by unzipping an APK and analyzing the resource files layer by layer, I’ve finally figured out this underlying mechanism. Let me start with my conclusions:</p><ol><li>The compiler first extracts all tag names, attribute names, and original text from the entire XML file, placing them at the beginning of the compiled XML to form a string constant pool array.</li><li>At the same time, all actual values are extracted and placed into the corresponding constant arrays in resources.arsc. The compiled XML only contains array references to resources.arsc.</li><li>Every compiled tag will have a start and an end, indicating the total length, header length, position in the source code, and the position of the tag name in the constant pool array. Attribute contents are completely replaced by references to the constant pool array and the constant arrays in resources.arsc.</li></ol><p>Let’s use a real example to better understand this mechanism.</p><p>Suppose we have the following line of code in our Android Studio project:</p><p>xml</p><pre>&lt;color name=&quot;purple_200&quot;&gt;#FFBB86FC&lt;/color&gt;</pre><p>When it is packaged into an APK, what transformations does it actually undergo?</p><p>1. String Pool: Replacing “Text” with “Coordinates”</p><p>As summarized above, the first thing the compiler does is “extraction.” The tag name &lt;color&gt;, the attribute name “name”, and the original text “purple_200” are all extracted, deduplicated, and placed at the very beginning of the binary XML file.</p><p>At the hexadecimal level, they look like this:</p><p>text</p><pre>63 6F 6C 6F 72 00  // &quot;color&quot; (0x63=c, 0x6F=o, 0x6C=l, 0x00 is the null terminator)<br>6E 61 6D 65 00     // &quot;name&quot;<br>70 75 72 70 6C 65 5F 32 30 30 00 // &quot;purple_200&quot;</pre><p>For extreme reading speed, the compiler builds an “offset array” in front of these strings at the beginning of the XML. When a tag needs to use “color”, it doesn’t store the English letters at all; instead, it only stores a coordinate like 0x00. Based on this coordinate, the system can instantly locate the real body of “color” in memory. This is why XML parsing is extremely fast — deduplication and offset addressing.</p><p>2. The Actual Values Go Inside the Giant Dictionary: resources.arsc</p><p>The string pool only stores “names”, so where did the color value go? The actual color value #FFBB86FC is extracted into the APK’s giant resource dictionary — resources.arsc.</p><p>Inside resources.arsc, it is assigned a unique 4-byte resource ID: 0x7f050001.</p><ul><li>0x7f: Package prefix (represents your App).</li><li>0x05: Type (represents color).</li><li>0x0001: Resource sequence number.</li></ul><p>In the compiled XML, where the attribute value was now only holds a 4-byte reference coordinate: 01 00 05 7f (little-endian 0x7f050001). There’s no trace of the color left in the XML; only a key to the dictionary remains.</p><p>3. Tag Structuring: TLV Header Control</p><p>Now let’s look at the tag itself. Every tag, whether start or end, becomes a strict TLV (Type-Length-Value) structure. Let’s look at the header of a start tag:</p><p>text</p><pre>02 01 24 00  // Type: 02 01 (Start Tag), Size: Total length 36 bytes<br>10 00 00 00  // HeaderSize: Header length 16 bytes<br>08 00 00 00  // LineNumber: Position in the source code (Line 8)<br>01 00 00 00  // Name Index: Go to the constant pool and find the 1st word (&quot;color&quot;)</pre><p>Why do we need both total length and header length? For the CPU to skip at maximum speed. After reading the header, the system immediately knows the body length by subtracting the header length from the total length. It then uses a pointer offset to traverse instantly, without needing to read line by line like text parsing.</p><p>4. The True Nature of Attributes: the Res_value Box</p><p>Immediately following the header is the body (attribute content) of the tag. Here, name=”purple_200&quot; becomes a reference to the constant pool, and its value is stuffed into a fixed 8-byte C++ struct called a Res_value box:</p><p>text</p><pre>08 00        // Size: 8 (Indicates this box is 8 bytes)<br>00           // Res0: Reserved bit<br>01           // DataType: 1 (Indicates this is a reference)<br>01 00 05 7f  // Data: 0x7f050001 (The coordinate from earlier)</pre><p>Once the system sees that the DataType is a reference, it stops parsing further and directly uses the coordinate in Data to fetch the actual value from resources.arsc.</p><p>5. What About Nested Tags?</p><p>What about a &lt;TextView&gt; inside a &lt;LinearLayout&gt;? They are arranged flatly in the binary. Inside the START_TAG of LinearLayout, the Size (total length) includes the sizes of all its internal child nodes. The system enters a hierarchy through a START_TAG and exits through an END_TAG. This is essentially a tree structure implemented in binary (similar to JSON bracket matching). This also explains why deeper layout nesting requires more time for the CPU to calculate node offsets, leading to slower app startup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=242e540b3637" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief peek into how Android manages memory, both when an app is installed and when it is running]]></title>
            <link>https://medium.com/@bearaddictedgames/a-brief-peek-into-how-android-manages-memory-both-when-an-app-is-installed-and-when-it-is-running-3705219a9216?source=rss-20efb6bce797------2</link>
            <guid isPermaLink="false">https://medium.com/p/3705219a9216</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Bearaddictedgames]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 03:58:29 GMT</pubDate>
            <atom:updated>2026-10-22T03:58:29.232Z</atom:updated>
            <content:encoded><![CDATA[<p>1. Installation and Optimization<br>A DEX file is highly compressed to reduce its storage size but also lead to inefficient execution. When Android installs an app, it will reorganize its structure, build indexes, and group commonly co-accessed ByteCodes to improve the cache hit rate. Following this, the system will utilize AOT to translate the most frequently accessed startup paths (guided by Cloud Baseline Profiles) into machine code to help accelerate app launches.</p><p>2. App Startup and Zero Copy<br>When an app is started, the system will use mmap to load necessary bytecode and machine code into Page Cache on-demand, which achieves zero-copy, avoiding the heavy lifting of copying data between kernel space and user space.</p><p>3. The JVM’s Perspective<br>From the JVM’s perspective, the memory is divided into three main sections:<br>1) Method Area: where class metadata resides, including inheritance hierarchies, method info, member variables, constant pool, and static variables.<br>2) Stack: for every method invoked, a stack frame is pushed. It stores input parameters, local variables (primitive values directly, and object references only), and execution state.<br>3) Heap: where we hold actual objects in memory.</p><p>4. Native and GPU Memory<br>They basically share the same RAM with the JVM memory, with the key difference being they are not strictly bounded by the app’s Java Heap limit (though they can still trigger the system’s Low Memory Killer if physical RAM is exhausted).<br>I will dive deep into native memory management in upcoming articles. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3705219a9216" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>