<?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 Sneha on Medium]]></title>
        <description><![CDATA[Stories by Sneha on Medium]]></description>
        <link>https://medium.com/@sneha_71656?source=rss-84e4a9435d53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6952py_sxHtzR9fN-0Z8aA.jpeg</url>
            <title>Stories by Sneha on Medium</title>
            <link>https://medium.com/@sneha_71656?source=rss-84e4a9435d53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:18:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sneha_71656/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[The 16 KB page size story (fixing your APK with zero assumed knowledge)]]></title>
            <link>https://medium.com/@sneha_71656/the-16-kb-page-size-story-fixing-your-apk-with-zero-assumed-knowledge-37ff00128403?source=rss-84e4a9435d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/37ff00128403</guid>
            <category><![CDATA[apk]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[16-kb-page-size]]></category>
            <category><![CDATA[google-play-store]]></category>
            <dc:creator><![CDATA[Sneha]]></dc:creator>
            <pubDate>Wed, 06 May 2026 00:10:12 GMT</pubDate>
            <atom:updated>2026-05-06T00:15:14.150Z</atom:updated>
            <content:encoded><![CDATA[<p>It started with this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*pAfNJrsmHMGy9HgzpZfKSA.png" /></figure><p>Cool. Great. Love to see a warning I’ve never seen before, containing words I technically know but have never had to care about, appearing on a Tuesday afternoon when I just wanted to build and test a button.</p><p><em>LOAD segments.</em> Not aligned. At <em>16 KB boundaries.</em></p><p>I know what 16 is. I know what KB is. I know what “not compatible” means and I don’t like it.</p><p>So I did what any self-respecting developer does. I Googled it, read the Android docs (helpful but dense), and eventually pieced together the full picture.</p><p>This blog is that full picture. Starting from the very beginning. No assumed knowledge. No skipping steps. Let’s go.</p><h3>First, Let’s Talk About How Your Phone Actually Runs Apps</h3><p><em>(Bear with me, this matters. I promise I’ll make it make sense.)</em></p><p>When you tap an app icon, your phone doesn’t just run the app. It has to load it, ie, copy pieces of it from storage (your phone’s flash memory) into RAM so the CPU can actually execute it.</p><p>Think of it this way:</p><ul><li><strong>Storage</strong> (128 GB, 256 GB) = your bookshelf. Books sit there doing nothing until you need them.</li><li><strong>RAM</strong> (8 GB, 12 GB) = your desk. You pull a book off the shelf and put it on your desk to actually read it.</li><li><strong>CPU</strong> = you. You can only read what’s on the desk.</li></ul><p>Simple enough. Now here’s the interesting bit.</p><p>Your phone doesn’t move one byte at a time from the shelf to the desk. That would be like walking to the bookshelf to get one word, coming back, reading it, going back for the next word. Exhausting.</p><p>Instead, the OS moves data in fixed-size <strong>chunks called pages</strong>. Every single time something moves between storage and RAM, it moves as a whole page. No more, no less.</p><p>For decades, on basically every Android device ever made, one page = <strong>4 KB</strong> (4,096 bytes).</p><h3>So What Changed?</h3><p>Simple answer: phones got <em>way</em> more powerful, and 4 KB pages started to feel like moving house one teaspoon at a time.</p><p>Modern flagship phones have 12–16 GB of RAM. Modern apps are enormous. When you’re managing gigabytes of memory with 4 KB chunks, you end up with <em>millions</em> of these chunks to track. The OS has to maintain a giant index called a <strong>page table</strong> that maps every chunk to its location in RAM.</p><p>Millions of entries in that index. Constant lookups. It adds up.</p><p>Apple noticed this first. When they launched Apple Silicon, they switched to <strong>16 KB pages</strong>. Fewer, bigger chunks. Less index overhead. Faster memory access. Better battery life.</p><p>Google went: <em>“…yeah okay fair point.”</em></p><p>And so, starting with <strong>Android 15</strong> and the <strong>Pixel 9</strong>, Android started supporting devices with 16 KB pages. More OEMs will follow. This is the future.</p><p>But here’s where it gets spicy for us developers.</p><h3>The Awkward Part: Your App Has Native Code In It</h3><p>Okay, time to introduce something you might not have dealt with before: <strong>.so files</strong>.</p><p>Most of your Android app is written in Kotlin or Java. That code gets compiled to bytecode and runs on the Android Runtime (ART). Fine. Normal. You know this.</p><p>But some code for performance-critical things, or for using C/C++ libraries is compiled directly to <strong>machine code</strong> for the specific CPU in the device. This is called <strong>native code</strong> or <strong>NDK code</strong>.</p><p>Native code gets bundled into your APK as files ending in .so — <strong>shared object files</strong>. Think of a .so like a .dll on Windows or a .dylib on Mac. It&#39;s a compiled library of native functions.</p><p>Here’s the thing though: <strong>even if you’ve never written a single line of C++</strong>, your app almost certainly has .so files in it. Because your dependencies brought them.</p><p>That fancy animation library? .so file. The PDF scanner SDK? .so file. The payment gateway? .so file. The root detection library? .so file. TensorFlow Lite? Absolutely packed with .so files.</p><p>Open up any APK (it’s just a ZIP, rename it to .zip and open it) and look inside the lib/ folder. You&#39;ll find them hiding in there, doing their thing quietly, never asking for attention.</p><p>Until now.</p><h3>Why Do .so Files Care About Page Size?</h3><p>Great question. Here’s where it gets a little technical, but I’ll keep it fun.</p><p>A .so file isn&#39;t just a blob of machine code. It&#39;s a structured file format called <strong>ELF</strong> — Executable and Linkable Format. Think of ELF like a really well-organised document with chapters.</p><p>Some of those chapters are labelled <strong>LOAD segments</strong>. These are the sections the OS literally <em>loads</em> into RAM when your app uses the library. There’s usually two:</p><ul><li>One for the <strong>code</strong> (the actual machine instructions — read-only, executable)</li><li>One for the <strong>data</strong> (global variables, configuration — readable and writable)</li></ul><p>Now here’s the key bit. Each LOAD segment has a field in its header that says: <strong>“hey OS, when you load me into RAM, please start me at a memory address that’s a multiple of this number.”</strong></p><p>That number is the <strong>alignment</strong>.</p><p>On a 4 KB page system: alignment is 0x1000 (= 4,096 bytes). Fine. On a 16 KB page system: alignment must be at least 0x4000 (= 16,384 bytes).</p><p>If your .so says 0x1000 but the OS is using 16 KB pages? The OS literally cannot load it correctly. The math doesn&#39;t work out. The addresses don&#39;t line up.</p><p><strong>Your app crashes.</strong></p><p>That’s what the warning is telling you. Your libraries are showing up to a 16 KB party dressed for a 4 KB party. They don’t fit through the door.</p><h3>Back to the Screenshot</h3><p>Now read that warning again:</p><blockquote>“Some libraries have LOAD segments not aligned at 16 KB boundaries”</blockquote><p>You can now translate this perfectly:</p><p><em>“These </em><em>.so files have told the OS they only need 4 KB alignment. But this device uses 16 KB pages. We can&#39;t load them. Your app will break.&quot;</em></p><p>And the culprits:</p><ul><li>libmyapplication.so — your own native code, compiled without the 16 KB flag</li><li>libtensorflowlite_jni.so — TensorFlow Lite, shipped as a prebuilt .so, old version, old alignment</li></ul><p>Two different problems. Two different fixes. Let’s do both.</p><h3>How to Actually See The Alignment Yourself</h3><p>You can inspect any .so file with a tool from your NDK called llvm-readelf. Here&#39;s how:</p><pre># Find it in your NDK (adjust path for your NDK version)<br>READELF=~/Library/Android/sdk/ndk/26.1.10909125/toolchains/llvm/prebuilt/darwin-x86_64/bin/llvm-readelf<br>$READELF -l libmyapplication.so | grep -E &quot;LOAD|Align&quot;</pre><p>A <strong>bad</strong> (4 KB) library looks like this:</p><pre>LOAD  0x000000  ...  Align: 0x1000   ← 4 KB. No good.<br>LOAD  0x0010a0  ...  Align: 0x1000   ← 4 KB. Still no good.</pre><p>A <strong>good</strong> (16 KB) library looks like this:</p><pre>LOAD  0x000000  ...  Align: 0x4000   ← 16 KB. <br>LOAD  0x004000  ...  Align: 0x4000   ← 16 KB.</pre><p>0x4000 in hex = 16,384 in decimal = 16 KB. That&#39;s what you want to see.</p><h3>Fix #1 — Your Own Native Code</h3><p>If your team has any CMakeLists.txt or Android.mk files in the project, those are your NDK build files. You&#39;re compiling native code.</p><p><strong>If you use CMake</strong> (CMakeLists.txt):</p><pre>target_link_options(mylib PRIVATE &quot;-Wl,-z,max-page-size=16384&quot;)</pre><p><strong>If you use ndk-build</strong> (Android.mk):</p><pre>LOCAL_MODULE    := myapplication<br>LOCAL_SRC_FILES := mycode.c<br>LOCAL_LDFLAGS   := -Wl,-z,max-page-size=16384   ← add this line<br><br>include $(BUILD_SHARED_LIBRARY)</pre><p>That -Wl,-z,max-page-size=16384 is a <strong>linker flag</strong>. You&#39;re telling the compiler: <em>&quot;when you assemble this library, make sure the LOAD segments are spaced out to 16 KB boundaries.&quot;</em></p><p>One line. Rebuild. Done. Your own .so is now 16 KB compliant.</p><h3>Fix #2 — Third-Party Libraries</h3><p>This one’s messier, because you don’t compile these yourself. They arrive as prebuilt .so files inside AARs (Android library packages) from your build.gradle.</p><p>Your options, in order of preference:</p><p><strong>Option A: Upgrade the dependency.</strong> Most popular libraries have already shipped 16 KB-compatible versions. Check their GitHub releases/changelog. For example, rootbeer (a popular root detection library) fixed this in version 0.1.0:</p><pre>// Before — 4 KB aligned, will fail<br>implementation(&quot;com.scottyab:rootbeer-lib:0.0.7&quot;)<br><br>// After - 16 KB aligned, ships with updated .so<br>implementation(&quot;com.scottyab:rootbeer-lib:0.1.1&quot;)</pre><p><strong>Option B: Pester the vendor.</strong> For closed-source SDKs — payment gateways, analytics, etc. — open a support ticket. The Play Store deadline is real and most vendors know it. They’re either already done or working on it.</p><p><strong>Option C: Cut it.</strong> If the library is non-critical and the vendor is unresponsive, consider removing it. The 16 KB requirement is a great forcing function for dependency hygiene.</p><p>There is no magic “realign this .so without rebuilding it&quot; option. The alignment is baked in at compile time.</p><h3>How to Audit Your Entire APK at Once</h3><p>Don’t check libraries one by one. Write a script, run it once, get the full picture:</p><pre>READELF=~/Library/Android/sdk/ndk/26.1.10909125/toolchains/llvm/prebuilt/darwin-x86_64/bin/llvm-readelf<br>APK=app/build/outputs/apk/debug/app-debug.apk<br>TMPDIR=$(mktemp -d)<br><br># APKs are just ZIPs - extract the arm64 libs<br>cd $TMPDIR &amp;&amp; unzip -q &quot;$APK&quot; &quot;lib/arm64-v8a/*.so&quot;<br>echo &quot;Library                               Alignment    Status&quot;<br>echo &quot;-----------------------------------------------------------&quot;<br>for f in $TMPDIR/lib/arm64-v8a/*.so; do<br>  name=$(basename $f)<br>  min_align=$($READELF -l $f 2&gt;/dev/null | awk &#39;/LOAD/{print $NF}&#39; | sort | head -1)<br>  dec=$((16#${min_align#0x}))<br>  [ &quot;$dec&quot; -ge 16384 ] &amp;&amp; label=&quot;✅ PASS&quot; || label=&quot;❌ FAIL&quot;<br>  printf &quot;%-40s %-12s %s\n&quot; &quot;$name&quot; &quot;$min_align&quot; &quot;$label&quot;<br>done<br>rm -rf $TMPDIR</pre><p>Run this after every dependency update. Make it part of your CI pipeline. It takes seconds and will save you from a Play Console rejection.</p><p><em>(Why only </em><em>arm64-v8a? Because 16 KB page kernels only exist on 64-bit ARM hardware. The other architectures — armeabi-v7a, x86 — are unaffected.)</em></p><h3>“But My App Doesn’t Crash on 16 KB Devices Right Now…”</h3><p>Correct, for now.</p><p>Android 15 includes a compatibility mode. If your library is 4 KB aligned, the kernel will emulate 4 KB page behaviour for your process. Your app won’t crash immediately.</p><p>But:</p><ol><li><strong>It’s slower.</strong> The kernel is doing extra work to fake 4 KB pages on a 16 KB system. Your app pays a performance tax it doesn’t need to pay.</li><li><strong>The compatibility mode will be removed.</strong> Google hasn’t announced when, but the intention is clear. The compat mode is a bridge, not a home.</li><li><strong>The Play Store deadline is not optional.</strong> From <strong>August 2025</strong>, new app submissions targeting API 35+ must be 16 KB compatible. If you miss it, your upload gets rejected. Not warned. <em>Rejected.</em></li></ol><p>So yes, your app might run today. It won’t submit to the Play Store next quarter.</p><h3>What Our Audit Looked Like (Before and After)</h3><p>We ran the script on our APK and found two failures:</p><pre>libkeys.so          0x1000   ❌ FAIL  ← our own NDK code<br>libtool-checker.so  0x10000  ❌ FAIL  ← rootbeer 0.0.7</pre><p><em>(Side note: </em><em>0x10000 is 64 KB — bigger than 16 KB, so you&#39;d think it passes. But Play Console tooling flags non-standard alignments too, and rootbeer&#39;s newer version ships a properly structured 16 KB aligned library anyway. Upgrade is the right call.)</em></p><p>Two fixes:</p><ol><li>Added LOCAL_LDFLAGS := -Wl,-z,max-page-size=16384 to Android.mk → libkeys.so now at 0x4000 ✅</li><li>Bumped rootbeer to 0.1.1 → libToolChecker.so (renamed in the new version) now at 0x4000 ✅</li></ol><p>Re-ran the script:</p><pre>libandroidx.graphics.path.so      0x4000   ✅ PASS<br>libbarhopper_v3.so                0x4000   ✅ PASS<br>libbugsnag-ndk.so                 0x4000   ✅ PASS<br>libbugsnag-plugin-android-anr.so  0x4000   ✅ PASS<br>libbugsnag-root-detection.so      0x4000   ✅ PASS<br>libc++_shared.so                  0x4000   ✅ PASS<br>libdatastore_shared_counter.so    0x4000   ✅ PASS<br>libimage_processing_util_jni.so   0x4000   ✅ PASS<br>libkeys.so                        0x4000   ✅ PASS<br>librive-android.so                0x4000   ✅ PASS<br>libsurface_util_jni.so            0x4000   ✅ PASS<br>libToolChecker.so                 0x4000   ✅ PASS<br>libts.so                          0x4000   ✅ PASS<br><br>=== 13 passed, 0 failed ===</pre><p>That’s it. That’s the whole thing. Warning gone. APK compatible. Tuesday saved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37ff00128403" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Spent a Year Teaching AI Tools About My Codebase. Here’s What Actually Worked]]></title>
            <link>https://medium.com/@sneha_71656/theres-a-moment-every-developer-hits-when-they-start-using-ai-coding-tools-seriously-2c68b354a1c6?source=rss-84e4a9435d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c68b354a1c6</guid>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sneha]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 22:56:05 GMT</pubDate>
            <atom:updated>2026-04-12T22:58:39.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IPaUwwdn4kcGvqbBrLnWA.png" /></figure><p>There’s a moment every developer hits when they start using AI coding tools seriously.</p><p>You’re excited. The tool is genuinely smart. It can write boilerplate, explain legacy code, suggest refactors. Then you ask it to generate something for <em>your</em> app — in <em>your</em> style, using <em>your</em> patterns — and it produces code that technically compiles but looks nothing like anything else in your codebase. Wrong component names. Wrong architecture structure. Wrong conventions throughout.</p><p>The AI isn’t dumb. It just doesn’t know you.</p><p>This is the story of how I spent a year solving that problem. I made mistakes I didn’t expect, discovered tools I didn’t know existed, and ended up somewhere genuinely surprising. Each chapter taught me something the previous one couldn’t.</p><h3>Chapter 1: The Monolith</h3><p>My first attempt at giving an AI tool context was the obvious one: write a big file explaining the project.</p><p>Cursor — an AI-powered code editor — had a feature for this called .cursorrules. One file at the root of your project. You write everything in it: the architecture, the coding conventions, the component library, the commit format, what files to never touch. Cursor reads it at the start of every session.</p><p>I wrote mine. It grew to about 700 lines. It covered the Android architecture pattern we used, our custom UI component library, our network layer conventions, git commit formats, what to avoid. It was dense and it was mine, and for a while it worked remarkably well.</p><p>Then I started noticing the noise problem.</p><p>When I was doing UI work, Cursor was loading all the network layer rules into context. When I was writing tests, it was loading the UI conventions. Everything was always loaded for everything. On a small project this is fine. On a codebase with distinct areas — UI, network, payments, analytics — it meant every prompt was carrying rules that had nothing to do with what you were actually working on.</p><p>I also discovered that 700 lines of rules is a nightmare to maintain. I’d update the UI conventions section and accidentally break the formatting of the network section because they were separated by three blank lines and a comment and I was editing at midnight.</p><p>The monolith had to go.</p><h3>Chapter 2: The Split — And What I Learned About How Rules Actually Work</h3><p>I broke the monolith into topic-specific files. Cursor supports this through a .cursor/rules/ directory where each file is a .mdc file (markdown with a small YAML header at the top).</p><p>The YAML header is what makes this system interesting:</p><pre>---<br>description: UI component conventions<br>globs: &quot;*.kt&quot;<br>alwaysApply: false<br>---</pre><p>globs means the rule only loads when you&#39;re working on matching files. alwaysApply: true means it loads into every prompt regardless. description helps the AI decide if the rule is relevant to what you&#39;re asking.</p><p>I split everything up by topic. UI rules. Network rules. Test rules. Navigation rules. Suddenly the noise was gone. When I was working on a network call, only the network rules loaded. Clean.</p><p>But here’s the thing I got wrong — and got corrected on by a developer who’d actually run controlled tests on this.</p><p>I assumed alwaysApply: true meant the rule would <em>fire</em> on every task. It doesn&#39;t. It means the rule is <em>loaded into context</em> on every task. The AI is still smart enough to skip it if the task doesn&#39;t match. Loaded into context is not the same as applied to output.</p><p>This matters for debugging. If Cursor is ignoring one of your rules, your first instinct might be to rewrite the rule to be more forceful. But sometimes the model is doing the right thing — it loaded the rule and correctly decided it wasn’t relevant. The real question is: does the rule fire when it <em>should</em>? Not: does it fire all the time?</p><p>I also discovered something else during this split: <strong>Cursor has two systems, not one.</strong></p><p>There are rules (.cursor/rules/*.mdc) which have the frontmatter, scoping control, and conflict priority. And there are skills (.cursor/skills/&lt;name&gt;/SKILL.md) which are simpler — no YAML, just markdown in a folder, no configuration overhead. When you&#39;re starting out, skills are less to think about. When you need precise control over when something loads and what it overrides, rules are the right tool.</p><p>And if you ever set up both a rule and a skill that say contradictory things — the rule wins. Every time. Worth knowing before you accidentally create a conflict and spend an hour wondering why the AI keeps ignoring one of them.</p><h3>Chapter 3: The Rules That Actually Work Were Written After Things Went Wrong</h3><p>Once the structure was in place, I ran into the deeper problem: the rules I’d written weren’t actually producing the right output.</p><p>I had a rule for generating new screens. I ran it. Cursor generated something that had the right overall shape but missed important details — it used a base component directly when it should have used a wrapper our team had built, it wired up navigation incorrectly, it didn’t follow the lifecycle pattern our codebase expected.</p><p>I went back to the rule and made it more specific. Ran it again. Better, but still gaps. Added more. Ran again.</p><p>Here’s what I eventually understood: <strong>the first version of any rule is a guess. The rules that actually work are written after you’ve seen them fail.</strong></p><p>The iteration loop became: write rule → generate code → observe the gap → ask why → sharpen the rule → repeat. Each failure revealed exactly what the rule hadn’t said clearly enough. Not vague enough — <em>specifically</em> unclear. Once I knew the specific gap, I could close it with one sentence.</p><p>The most useful thing I found was running this loop with Cursor as a collaborator. When the output was wrong, I’d explain what I expected and what I got, then ask: <em>“Based on the rule we just wrote, what’s missing that would have produced this output?”</em></p><p>Cursor would look at its own rule and point to the gap. We’d fix it together.</p><p>One rule that started as 50 lines of rough guidance became a 190-line step-by-step sequence — not because I planned that upfront, but because each generation failure added one more precise instruction. You don’t write the final version of a rule. You earn it.</p><p>A quick illustration of what that difference looks like in practice:</p><pre>❌ Before iteration:<br>&quot;Use our design system components for UI.&quot;</pre><pre>✅ After iteration:<br>&quot;Never create a custom button. Always use PopButton with a style <br>parameter (.primary or .secondary). Do not pass color directly. <br>See HomeScreen.kt line 42 for a reference usage.&quot;</pre><p>The second version has no room for misinterpretation. The first is a wish. The second is a contract.</p><h3>Chapter 4: A Different Tool — And Why the Same Approach Didn’t Work</h3><p>Around this time I started using Claude Code for a second project. Claude Code is a terminal-based AI — less focused on code generation from prompts, more focused on reasoning, reviewing, and working with you through complex tasks.</p><p>It has its own context system. Skills live in .claude/skills/ as SKILL.md files inside named subdirectories. There&#39;s also a CLAUDE.md file at the project root for project-wide context.</p><p>I approached it the same way I’d approached Cursor: write procedural, step-by-step instructions. “When creating a screen, do step 1, step 2, step 3.”</p><p>It felt wrong almost immediately. Claude already understood general software architecture. I was explaining things it didn’t need explained. And yet the output still missed things — not structural things, but <em>our</em> things. It used a function our codebase had deprecated. It called a network service in a way we’d explicitly moved away from. It sent analytics through a direct call when it was supposed to go through a wrapper.</p><p>These weren’t gaps in Claude’s general knowledge. They were gaps in its knowledge of <em>us</em>. Decisions our team had made. History we’d lived through. The deprecated function existed because we’d had bugs with it. The wrapper existed because we once had six different error-handling patterns and it was chaos.</p><p>None of that was in the code. It was in our heads.</p><p><strong>This is the insight that changed how I wrote skills: Claude didn’t need templates. It needed institutional memory.</strong></p><p>Templates tell the AI what structure to produce. Institutional memory tells the AI the decisions your team already made, why they made them, and what not to undo. These are different things requiring different writing.</p><p>I rewrote the skills entirely. Instead of “here’s how to build a screen,” I wrote “here’s what a new engineer would need to know before touching this codebase.” The hard-won rules. The gotchas. The “we tried that once and here’s what broke.” The things that don’t appear in any README but that a good senior engineer would tell you in your first week.</p><p>I also organized it hierarchically. The main skill file is a brief — a one-page orientation. Separate reference files go deep on specific areas: the network layer, the payment module navigation (which works differently from the rest of the app), the analytics system, the component library. Claude reads only what’s relevant to what you’re actually doing.</p><p>The output changed immediately. Claude stopped undoing the things we’d worked to establish.</p><h3>Chapter 5: When Context Enables Judgment, Not Just Generation</h3><p>Once the institutional memory was solid, I tried something I hadn’t attempted with Cursor: code review.</p><p>I wrote a skill that described how to review a pull request on our codebase — a checklist with categories: architecture, navigation, UI patterns, tests, analytics, security, code quality. For each item, a clear standard. For the security category specifically, guidance on what counts as sensitive data in a financial app, and how to spot it in logs or analytics calls.</p><p>I gave Claude a pull request to review.</p><p>It went through every category. And it flagged something: a log statement that included a value that looked like it could be a user’s financial account identifier. It wasn’t following a template. It was <em>reading the code</em> and making a <em>judgment call</em> about a potential privacy risk.</p><p>This is something Cursor rules genuinely can’t do. A rule is an instruction for generating code. It can’t evaluate whether code someone else already wrote is safe, or whether an architecture decision is sound, or whether a PR introduces a regression in a pattern you’ve worked hard to maintain. Cursor rules are for <em>creating</em>. Claude skills — when they carry enough context — enable <em>evaluating</em>.</p><p>Not better or worse. Just a different thing entirely. Once I understood which tasks required generation and which required judgment, I stopped trying to use both tools for everything and started routing work to the one that was actually suited for it.</p><h3>Chapter 6: The Problem Nobody Talks About — Two Tools, Two Configs, One Codebase</h3><p>Here’s where things got messy in a way I didn’t anticipate.</p><p>I was now using both tools on the same codebase. Cursor for code generation. Claude Code for reasoning, reviewing, and navigating complex work. Two tools. Two separate config systems. Zero coordination between them.</p><p>Within a few weeks, they were drifting.</p><p>I’d update a convention in the Cursor rules and forget the Claude skill that covered the same area. I’d add a new pattern to the Claude skill and not think about whether Cursor needed to know about it. The two tools were supposed to share knowledge about the same codebase, but they were reading from separate files that had started diverging the moment I made my first update.</p><p>The elegant solution I came across — and immediately adopted — was to treat the config as a separate layer that both tools read from.</p><p>Create a single .ai/ directory at the project root. Put all your rules and skills there, as plain markdown. Then point both tools at it:</p><pre>.ai/<br>  rules/<br>    ui-conventions.md<br>    network-patterns.md<br>    testing.md<br>  skills/<br>    pr-review/SKILL.md<br>    component-guide/SKILL.md<br>  hooks/<br>    shared-logic.sh</pre><pre>.cursor/<br>  rules/ui-conventions.mdc → symlink to .ai/rules/ui-conventions.md<br>  skills/pr-review → symlink to .ai/skills/pr-review/</pre><pre>.claude/<br>  rules/ → symlink to .ai/rules/<br>  skills/ → symlink to .ai/skills/</pre><p>One source of truth. Both tools read from the same files. Update a rule once, both tools get it automatically.</p><p>Adding a new rule becomes:</p><ol><li>Create .ai/rules/my-rule.md</li><li>Add a symlink in .cursor/rules/</li><li>Done — Claude picks it up automatically through the directory symlink</li></ol><p>The framing shift this produced was useful: the knowledge isn’t Cursor knowledge or Claude knowledge. It’s <em>project</em> knowledge. The tools are just different readers.</p><p>If I were starting a new project today, I’d set up the .ai/ structure before writing a single line of code. The config first. Not because it&#39;s fun to set up, but because doing it at the end means you&#39;ll either never do it or do it badly.</p><h3>Chapter 7: When the Library Maintains Its Own Documentation</h3><p>A few days ago, a colleague on the iOS team showed me something that made every approach I’d described feel like it was missing a layer.</p><p>The iOS team maintained a shared component library — a Swift package consumed by the main app. Dozens of components, each with a specific public API: configuration options, initializer parameters, delegate methods. The kind of thing that changes with every release.</p><p>The problem: any skill file documenting this library was guaranteed to go stale. A component gets a new parameter. An initializer signature changes. A new variant gets added. The skill doesn’t know. It just sits there telling Claude the wrong thing with full confidence.</p><p>Their first solution was the obvious one: write a skill file that documents every component. It worked for about two weeks. Then the library had a release. The skill was out of date. Back to hallucination.</p><p>Manual documentation always decays. The only question is how fast.</p><p>Their actual solution was different in kind, not just degree.</p><p>They built a skill — a command you can run — that does the following:</p><ol><li>Reads the actual Swift source files of the component library</li><li>Extracts every public API: config structs, initializer parameters, delegate protocols, enumerations</li><li>Rewrites its own SKILL.md based on what it finds</li></ol><p>Claude isn’t being <em>told</em> about the component APIs. It’s <em>reading</em> the source code and <em>writing its own understanding of it</em>. The documentation is derived from the source, not maintained alongside it.</p><p>Then they chained it with two hooks:</p><p><strong>An automatic copy hook:</strong> The moment the skill file is updated in the repository, it’s copied to a global Claude config location on every developer’s machine. Updated knowledge arrives automatically — no one has to opt in.</p><p><strong>A git sync hook:</strong> When a developer pulls the latest code from the main branch, the global skill resyncs automatically. Pulling new component code also pulls updated Claude knowledge about that component code.</p><p>Onboarding a new developer onto this system:<br>git config core.hooksPath scripts/hooks</p><p>One command. From that point forward, every git pull keeps their Claude knowledge current.</p><p>The framing shift here is significant: the component library is now responsible for keeping Claude informed about itself. The <em>library</em> ships its own Claude context as a first-class artifact, alongside the code. Consumers don’t maintain a component catalog — they just pull.</p><h3>What the Progression Actually Looks Like</h3><p>Looking back at the full arc:</p><p><strong>Stage one — The monolith.</strong> One big rules file. Works until it doesn’t. Too much noise, too hard to maintain.</p><p><strong>Stage two — The split.</strong> Topic-specific rules with scoping. Learn that both Cursor and Claude have rules <em>and</em> skills, with different trade-offs. Learn that loaded ≠ applied. Learn that rules only get good through iteration.</p><p><strong>Stage three — Institutional memory.</strong> Stop writing templates. Start writing the decisions your team made and why. Organize hierarchically: a brief at the top, deep reference files underneath. This is what unlocks correct output without constant correction.</p><p><strong>Stage four — Judgment.</strong> When context is rich enough, the AI stops just generating and starts evaluating. Code review. Security checks. Architecture assessments. Different cognitive mode, different class of task.</p><p><strong>Stage five — Single source of truth.</strong> When you’re using multiple AI tools on the same codebase, the config needs to live in one place. Tool-agnostic. Both readers point at the same files.</p><p><strong>Stage six — Self-maintaining knowledge.</strong> The gap between source code and AI context closes automatically. The library is the documentation. Changes propagate through hooks. Humans write the mechanism; the AI maintains the content.</p><p>Each stage makes the previous one look incomplete. Each one unlocks something the previous one couldn’t. And I’m reasonably confident the story doesn’t end at stage six.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c68b354a1c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Baseline Profiles decoded]]></title>
            <link>https://medium.com/@sneha_71656/baseline-profiles-decoded-74b9c6c0d71c?source=rss-84e4a9435d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/74b9c6c0d71c</guid>
            <category><![CDATA[app-performance]]></category>
            <category><![CDATA[baseline-profiles]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Sneha]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 19:46:24 GMT</pubDate>
            <atom:updated>2026-01-19T19:46:24.797Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Unlock Android Performance Secrets — Sneha" src="https://cdn-images-1.medium.com/max/1024/1*6LIdLII3-JFh64pqGSX_Rg.jpeg" /></figure><p>Baseline Profiles can improve your Android app’s startup time by 30–40% with minimal effort. This blog shows you exactly how to implement and measure them, using real production code examples.</p><p>Table of Contents</p><p>1. Introduction: The Performance Problem<br>2. What Are Baseline Profiles?<br>3. How Baseline Profiles Work?<br>4. Setting Up Baseline Profiles<br>5. Generating Baseline Profiles<br>6. Benchmarking: Measuring What Matters<br>7. Behind the Scenes: How Profiles Are Generated<br>8. Real-World Results<br>9. Best Practices and Tips</p><h3>Introduction: The Performance Problem</h3><p>Every Android developer knows the pain when your app looks great, works perfectly, but those first few seconds after launch? Janky. Slow. Frustrating for users.</p><p>The culprit? <strong>JIT (Just-In-Time) compilation</strong>. Every time a user launches your app for the first time, Android has to figure out which parts of your code to optimize. This happens while the user is waiting, resulting in<br>- 🐌 Slow cold starts (the first launch after installation)<br>- 😤 Poor first impressions<br>- 📉 Lower retention rates</p><p><strong>Baseline Profiles</strong> solve this by telling Android: “Hey, these specific code paths are critical. Compile them ahead of time!”</p><h3>What Are Baseline Profiles?</h3><p>Baseline Profiles are essentially <strong>rules files </strong>that identify the most critical code paths in your app. They’re simple text files that list methods and classes that should be compiled AOT (Ahead-of-Time) rather than JIT.</p><h4>Here’s what a real Baseline Profile looks like:</h4><pre>HSPLandroidx/activity/ComponentActivity;-&gt;&lt;init&gt;()V<br>HSPLandroidx/activity/ComponentActivity;-&gt;onCreate(Landroid/os/Bundle;)V<br>HSPLandroidx/compose/ui/platform/ComposeView;-&gt;setContent(Lkotlin/jvm/functions/Function2;)V<br>PLcom/example/fintech/ui/MainActivity;-&gt;onCreate(Landroid/os/Bundle;)V<br>HSPLcom/example/fintech/home/HomeScreen;-&gt;HomeScreenContent(Landroidx/compose/runtime/Composer;I)V</pre><p>Each line represents a method in your app. The prefixes (H, S, P, L) tell Android how to optimize these methods. We’ll explore exactly how these are generated later in the blog.</p><p><strong>The Impact<br></strong>When you ship your app with Baseline Profiles, you achieve:<br>• 30–40% faster app startup<br>• Smoother initial navigation<br>• Better performance on low-end devices<br>• and, Improved user experience on fresh installs</p><h3>How Baseline Profiles Work?</h3><p><strong>Without Baseline Profiles<br></strong>User launches app<br> ↓<br>Android loads APK<br> ↓<br>JIT compiler runs (during app usage)<br> ↓<br>App gradually gets faster as methods are compiled</p><p><strong>With Baseline Profiles<br></strong>User installs app from Play Store<br> ↓<br>Play Store pre-compiles methods listed in profiles<br> ↓<br>User launches app<br> ↓<br>Critical code already optimized ✨<br> ↓<br>Fast startup from the very first launch!</p><p>The magic happens during installation. Google Play uses your Baseline Profile to perform <strong>cloud-based AOT compilation</strong> before the user even launches your app.</p><h3>Setting Up Baseline Profiles</h3><p>Let’s walk through setting up Baseline Profiles in your project, using real examples from a production fintech app.</p><p><strong>Step 1: Create a Baseline Profile Module</strong></p><p>First, add the baseline profile module to your <em>settings.gradle.kts</em>:</p><pre>include(&quot;:baselineprofile&quot;)</pre><p><strong>Step 2: Configure the Baseline Profile Module</strong></p><p>Create <em>baselineprofile/baselineprofile.gradle.kts</em>:</p><pre>plugins {<br> id(&quot;com.android.test&quot;)<br> id(&quot;org.jetbrains.kotlin.android&quot;)<br> id(&quot;androidx.baselineprofile&quot;)<br>}<br><br>android {<br> namespace = &quot;com.example.fintech.baselineprofile&quot;<br> compileSdk = 34<br> defaultConfig {<br>  minSdk = 24<br>  targetSdk = 34<br>  testInstrumentationRunner = &quot;androidx.test.runner.AndroidJUnitRunner&quot;<br>  // Important: Workaround for stability issues<br>  testInstrumentationRunnerArguments[&quot;androidx.benchmark.killProcessDelayMillis&quot;] = &quot;10000&quot;<br> }<br> // Create a build type to match your app&#39;s benchmark build type<br> buildTypes {<br>  create(&quot;release&quot;) {}<br>  create(&quot;baselineprof&quot;) {<br>   initWith(getByName(&quot;release&quot;))<br>   signingConfig = signingConfigs.getByName(&quot;debug&quot;)<br>   matchingFallbacks.addAll(listOf(&quot;baselineprof&quot;, &quot;release&quot;))<br>  }<br> }<br> // Point to your app module<br> targetProjectPath = &quot;:app&quot;<br> // Enable the benchmark to run separately from the app process<br> experimentalProperties[&quot;android.experimental.self-instrumenting&quot;] = true<br> // Configure Gradle Managed Device for profile generation<br> testOptions.managedDevices.devices {<br>  create&lt;ManagedVirtualDevice&gt;(&quot;pixel6Api34&quot;) {<br>   device = &quot;Pixel 6&quot;<br>   apiLevel = 34<br>   systemImageSource = &quot;google&quot;<br>   }<br>  }<br> }<br> // Configure how baseline profiles are generated<br> baselineProfile {<br>  managedDevices += &quot;pixel6Api34&quot;<br>  useConnectedDevices = false<br>  enableEmulatorDisplay = false // Set to true for debugging<br> }<br>dependencies {<br>implementation(&quot;androidx.test.ext:junit:1.1.5&quot;)<br>implementation(&quot;androidx.test.espresso:espresso-core:3.5.1&quot;)<br>implementation(&quot;androidx.test.uiautomator:uiautomator:2.3.0&quot;)<br>implementation(&quot;androidx.benchmark:benchmark-macro-junit4:1.2.3&quot;)<br>}</pre><p><strong>Step 3: Configure Your App Module</strong></p><p>In your <em>app/build.gradle.kts</em>, add the baseline profile plugin and dependency:</p><pre>plugins {<br> id(&quot;com.android.application&quot;)<br> // … other plugins<br> id(&quot;androidx.baselineprofile&quot;)<br>}<br>android {<br> // … existing configuration<br> buildTypes {<br>  release {<br>   isMinifyEnabled = true<br>   // … other release config<br>  }<br>  // Create a special build type for benchmarking<br>  create(&quot;baselineprof&quot;) {<br>   initWith(getByName(&quot;release&quot;))<br>   signingConfig = signingConfigs.getByName(&quot;debug&quot;)<br>   matchingFallbacks.addAll(listOf(&quot;baselineprof&quot;, &quot;release&quot;))<br>   proguardFiles(&quot;benchmark-rules.pro&quot;) // Lighter proguard rules<br>  }<br> }<br>}<br>dependencies {<br> // … other dependencies<br> // Link to the baseline profile module<br> baselineProfile(project(&quot;:baselineprofile&quot;))<br> // Profile installer for runtime support<br> implementation(&quot;androidx.profileinstaller:profileinstaller:1.3.1&quot;)<br>}<br>// Configure which variants should generate profiles<br>baselineProfile {<br> saveInSrc = true // Save generated profiles in src/main<br> variants.register(&quot;qaRelease&quot;) {<br>  automaticGenerationDuringBuild = false // Enable when needed<br> }<br> variants.register(&quot;prodRelease&quot;) {<br>  automaticGenerationDuringBuild = false<br> }<br>}</pre><p><strong>Step 4: Add Gradle Dependencies</strong></p><p>In your project’s <em>libs.versions.toml</em>:</p><pre>[versions]<br>androidx-benchmark = &quot;1.2.3&quot;<br>androidx-profileinstaller = &quot;1.3.1&quot;<br>[plugins]<br>androidx-baselineprofile = { id = &quot;androidx.baselineprofile&quot;, version = &quot;1.2.3&quot; }<br>[libraries]<br>androidx-benchmark-macro-junit4 = { module = &quot;androidx.benchmark:benchmark-macro-junit4&quot;, version.ref = &quot;androidx-benchmark&quot; }<br>androidx-profileinstaller = { module = &quot;androidx.profileinstaller:profileinstaller&quot;, version.ref = &quot;androidx-profileinstaller&quot; }</pre><h3>Generating Baseline Profiles</h3><p>Now comes the exciting part - generating the actual profiles by simulating real user journeys.</p><p><strong>Creating a Profile Generator</strong></p><p>Profile generators are<strong> instrumented tests</strong> that simulate real user journeys. Think of them as robots that use your app exactly like a human would, while Android watches and records which code gets executed.</p><p><strong>The Base Scaffold Pattern</strong></p><p>First, let’s create a reusable base class. This is a common pattern that makes creating multiple profile generators easier. Here’s the scaffold with detailed explanations:</p><pre>package com.example.fintech.baselineprofile.profilegen<br><br>import android.os.Build<br>import androidx.annotation.RequiresApi<br>import androidx.benchmark.macro.MacrobenchmarkScope<br>import androidx.benchmark.macro.junit4.BaselineProfileRule<br>import androidx.test.ext.junit.runners.AndroidJUnit4<br>import androidx.test.filters.LargeTest<br>import org.junit.Rule<br>import org.junit.Test<br>import org.junit.runner.RunWith<br><br>/**<br> * Scaffold for creating baseline profile generators.<br> * Each generator simulates a critical user journey.<br> */<br>@RunWith(AndroidJUnit4::class)<br>@LargeTest  // ← Tells test runner this is a long-running test (can take 5-10 min)<br>abstract class BaselineProfileGeneratorScaffold {<br><br>    @RequiresApi(Build.VERSION_CODES.P)  // ← Requires Android 9+ or rooted device<br>    @get:Rule<br>    val rule = BaselineProfileRule()  // ← The magic! This instruments your app<br><br>    /**<br>     * Should this profile be included in startup-prof.txt?<br>     * Only use true for app launch and immediately visible screens.<br>     * <br>     * Think carefully about this:<br>     * ✅ TRUE = &quot;Users see this immediately after launch&quot; (Home, Dashboard)<br>     * ❌ FALSE = &quot;Users navigate here later&quot; (Settings, Deep features)<br>     */<br>    abstract fun shouldIncludeInStartupProfile(): Boolean<br><br>    /**<br>     * Define your user journey here using UI Automator.<br>     * This is where you simulate real user behavior - clicking, scrolling, etc.<br>     */<br>    abstract fun MacrobenchmarkScope.profileBlock()<br><br>    @RequiresApi(Build.VERSION_CODES.P)<br>    @Test<br>    fun profileGenerator() {<br>        rule.collect(<br>            packageName = getApplicationPackageToTest(),<br>            maxIterations = 5,  // ← Run 5 times to get consistent data<br>            // This flag determines whether methods get &#39;S&#39; or &#39;P&#39; in HSPL<br>            includeInStartupProfile = shouldIncludeInStartupProfile(),<br>        ) {<br>            // Your profileBlock() runs here, 5 times in a row<br>            profileBlock()<br>        }<br>    }<br>}</pre><p>Let’s break down what each part does:</p><p>1.<strong> BaselineProfileRule() <br></strong>This is the heart of the operation. When this rule runs, it:<br>- Launches your app in a special profiling mode<br>- Tracks every single method call<br>- Records timing, frequency, and context<br>- Generates the HSPL flags based on observed behavior</p><p>2. <strong>maxIterations = 5</strong> <br>Why run it 5 times?<br>- <strong>First run</strong> might be slow (cold caches, JIT warmup)<br>- <strong>Second run</strong> might have cached assets<br>- <strong>Third+</strong> runs give consistent patterns<br>- Android averages all 5 runs to determine “normal” behavior<br>- This eliminates outliers and gives accurate profiles</p><p>3. <strong>abstract fun profileBlock()<br></strong>This is YOUR part! You define:<br>- Launch the app<br>- Navigate to a screen<br>- Tap buttons<br>- Scroll lists<br>- Basically, anything a real user would do</p><p>4. <strong>shouldIncludeInStartupProfile()<br></strong>This is critical!<br>- if true → Methods go to <em>startup-prof.txt</em> → AOT compiled before first launch<br>- if false → Methods go only to <em>baseline-prof.txt </em>→ Compiled in background<br>- Wrong choice? Your settings screen might slow down startup!</p><p>💡 Pro Tip: Create this scaffold once, then every new profile generator extends it. Much cleaner than copy-pasting and redundant code</p><p><strong>Example: Home Screen QR Scanner Flow</strong></p><p>Now let’s see this in action! We’ll create a profile generator for one of the most common user journeys in a fintech app: <br>Launching the app and opening the QR scanner to make a payment.</p><p><strong>Why profile this?</strong> Because users do this ALL THE TIME:</p><p>1. Open app → Need to pay someone → Tap QR scanner<br>If this flow is slow, users notice. If it’s fast, they love your app. Let’s make it fast!</p><p>Here’s the complete generator with line-by-line explanations:</p><pre>package com.example.fintech.baselineprofile.profilegen<br><br>import android.content.Intent<br>import android.util.Log<br>import androidx.benchmark.macro.MacrobenchmarkScope<br>import androidx.test.uiautomator.By<br><br>/**<br> * Generates baseline profile for QR screen launch from Home.<br> * This is a critical user journey that happens frequently.<br> */<br>class HomeQrProfileGenerator : BaselineProfileGeneratorScaffold() {<br><br>    private val TAG = &quot;BaselineTestHomeQr&quot;<br>    private var isSignupDone = false  // ← Shared state across iterations<br><br>    // ✅ TRUE because users see QR button immediately after launch<br>    override fun shouldIncludeInStartupProfile(): Boolean = true<br><br>    override fun MacrobenchmarkScope.profileBlock() {<br>        // 1️⃣ LAUNCH THE APP<br>        startActivityAndWait(Intent().apply {<br>            setClassName(getApplicationPackageToTest(), &quot;com.example.fintech.ui.MainActivity&quot;)<br>        })<br>        Log.i(TAG, &quot;App launched&quot;)<br><br>        // 2️⃣ HANDLE SYSTEM DIALOGS<br>        // Sometimes Android shows ANR or crash dialogs - dismiss them<br>        dismissSystemAlert()<br><br>        // 3️⃣ ONE-TIME SETUP (only in first iteration)<br>        if (!isSignupDone) {<br>            Log.i(TAG, &quot;Starting Signup&quot;)<br>            isSignupDone = true  // Don&#39;t repeat this in iterations 2-5<br>            <br>            setScreenTimeout(600000L)  // 10 min - prevent screen from sleeping<br>            allowPermissions()         // Pre-grant camera, location, etc.<br>            signIn()                   // Automated login with test account<br>        }<br>        <br>        device.waitForIdle()  // Wait for animations to complete<br>        Log.i(TAG, &quot;SignIn completed, preparing to launch home screen&quot;)<br><br>        // 4️⃣ ENSURE APP IS READY<br>        ensureAppReady()  // Dismiss any late dialogs<br><br>        // 5️⃣ NAVIGATE TO HOME SCREEN<br>        startActivityAndWait(Intent().apply {<br>            setClassName(getApplicationPackageToTest(), &quot;com.example.fintech.ui.MainActivity&quot;)<br>        })<br>        device.waitForIdle(10000)  // Give it time to load balance, cards, etc.<br>        <br>        ensureAppReady()<br>        Log.i(TAG, &quot;Home screen launched&quot;)<br><br>        // 6️⃣ THE ACTUAL USER FLOW: Tap QR Scanner<br>        // This is what we&#39;re profiling! Everything above was setup.<br>        try {<br>            device.waitAndFindObject(<br>               By.res(getApplicationPackageToTest(), &quot;qr_button&quot;), // Find by accessibility description<br>               timeout = 45000L / Wait up to 45 seconds<br>            ).click()<br>            Log.i(TAG, &quot;Successfully clicked qr_button&quot;)<br>        } catch (e: Exception) {<br>            // If we can&#39;t find the button, something&#39;s wrong - log and fail<br>            Log.e(TAG, &quot;Failed to find qr_button&quot;, e)<br>            throw e<br>        }<br>        <br>        device.waitForIdle()  // Wait for QR screen to load<br><br>        // 7️⃣ CLEAN UP for next iteration<br>        // Kill the process so iteration 2 starts fresh (cold start)<br>        killProcess()<br>    }<br>}</pre><p>Let’s unpack this code:</p><p><strong>The Class Structure</strong></p><pre>private var isSignupDone = false</pre><p><strong>Why is this outside the function?</strong> Because the test runner resets local variables between test runs, but class-level variables persist! We only want to do signup once, not all 5 times.</p><pre>override fun shouldIncludeInStartupProfile(): Boolean = true</pre><p><strong>Why true? </strong>The QR scanner is a primary feature. Users see the QR button immediately after launch. If we set this to <em>false</em>, the QR code wouldn’t be pre-compiled, and users would experience lag the first time they try to scan.</p><p><strong>The Flow Breakdown</strong></p><p>1. Launch (Line 5–8)</p><pre>startActivityAndWait(Intent().apply {<br>    setClassName(packageName, &quot;MainActivity&quot;)<br>})</pre><p>This is like tapping your app icon. <em>startActivityAndWait()</em> blocks until the activity is visible, so we know the app is ready before proceeding.</p><p>2. Dismiss System Dialogs (Line 10–12)</p><pre>dismissSystemAlert()</pre><p>Sometimes Gradle Managed Devices show “App isn’t responding” dialogs. These would break our test, so we dismiss them proactively.</p><p>3. One-Time Setup (Line 14–23)</p><pre>if (!isSignupDone) {<br>    // ... setup code<br>}</pre><p><strong>The problem:</strong> We need a logged-in user to see the home screen, but we don’t want to profile the login flow (that’s a different generator!).</p><p><strong>The solution:</strong> Do login once in iteration 1, then skip it in iterations 2–5. This way we profile ONLY the home → QR flow.</p><pre>setScreenTimeout(600000L) // 10 minutes</pre><p>Tests can take time. If the screen sleeps, the test fails. So we prevent sleep.</p><pre>allowPermissions()</pre><p>We grant camera/location permissions via ADB. Why? Because permission dialogs would interrupt the flow we’re trying to profile. We want to measure “normal app usage,” not “first-time permission flow.”</p><pre>signIn()</pre><p>This helper function fills in email/OTP/etc. automatically. More on this below!</p><p>4. Ensure Ready (Line 28)</p><pre>ensureAppReady()</pre><p>Another safety check. Wait for UI to stabilize, dismiss any late dialogs.</p><p>5. Navigate to Home (Line 31–39)</p><pre>startActivityAndWait(…)<br>device.waitForIdle(10000)</pre><p>We launch MainActivity again (in case we’re not there) and wait 10 seconds. Why so long? Because the home screen might:<br>- Load balance from network<br>- Fetch account details<br>- Animate banners<br>- Load images</p><p>We want all of that ready before we click the QR button.</p><p>6. The Actual Flow</p><pre>device.waitAndFindObject(<br>    By.res(getApplicationPackageToTest(), &quot;qr_button&quot;),<br>    timeout = 45000L<br>).click()</pre><p><strong>This is it!</strong> This is the user action we’re profiling. Everything before was setup.</p><p>- <em>By.res(“qr_button”)</em> — Finds UI element by its resource ID<br>(make sure you set `contentDescription` in your Compose/XML!)<br>- <em>timeout = 45000L</em> — Wait up to 45 seconds for it to appear<br>- <em>.click() </em>— Tap it!</p><p><strong>Why such a long timeout?</strong> Sometimes on slow devices or flaky network, the home screen takes time. Better to wait than fail the test.</p><p>7. Clean Up (Line 56)</p><pre>killProcess()</pre><p>Force-kill the app so the next iteration starts from scratch (cold start). This ensures consistent profiling across all 5 runs.</p><p>🎯 <strong>Key Insight</strong>: Notice that 80% of the code is setup/cleanup. Only ~20% is the actual user journey. That’s normal! Profile generators need to be robust and handle edge cases.</p><p><strong>Helper Extensions for UI Automation</strong></p><p>You’ll notice the code above uses helper functions like <em>waitAndFindObject()</em>, <em>allowPermissions()</em>, and <em>signIn()</em>. These aren’t built-in- we create them! Let’s build a toolkit of reusable utilities that make writing profile generators much easier.</p><p><strong>Why create helpers?</strong> Because you’ll write multiple profile generators (Dashboard flow, Configuration flow, Transaction flow, etc.), and they all need similar operations. Write once, use everywhere!</p><pre>package com.example.fintech.baselineprofile<br><br>import android.Manifest<br>import android.os.Build<br>import androidx.benchmark.macro.MacrobenchmarkScope<br>import androidx.test.uiautomator.By<br>import androidx.test.uiautomator.BySelector<br>import androidx.test.uiautomator.UiDevice<br>import androidx.test.uiautomator.UiObject2<br>import androidx.test.uiautomator.Until<br><br>/**<br> * Waits until an object with [selector] is visible on screen.<br> * Throws AssertionError if element is not found within timeout.<br> */<br>fun UiDevice.waitAndFindObject(<br>    selector: BySelector, <br>    timeout: Long = 30000L  // Default: 30 seconds<br>): UiObject2 {<br>    // Wait for element to appear<br>    if (!wait(Until.hasObject(selector), timeout)) {<br>        // Not found? Throw descriptive error<br>        throw AssertionError(<br>            &quot;Element not found on screen in ${timeout}ms (selector=$selector)&quot;<br>        )<br>    }<br>    // Found! Return it so we can .click(), .setText(), etc.<br>    return findObject(selector)<br>}<br><br>/**<br> * Pre-grants dangerous permissions via ADB to avoid permission dialogs<br> * during profiling. We don&#39;t want to profile &quot;grant permission&quot; flow!<br> */<br>internal fun MacrobenchmarkScope.allowPermissions() {<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>        listOf(<br>            Manifest.permission.CAMERA,            // For QR scanning<br>            Manifest.permission.POST_NOTIFICATIONS, // For payment alerts<br>            Manifest.permission.READ_PHONE_STATE,   // For phone verification<br>        ).forEach { permission -&gt;<br>            // Execute ADB command: pm grant &lt;package&gt; &lt;permission&gt;<br>            device.executeShellCommand(&quot;pm grant $packageName $permission&quot;)<br>        }<br>    }<br>}<br><br>/**<br> * Dismisses system alert dialogs (ANR, crash dialogs, &quot;App isn&#39;t responding&quot;)<br> * <br> * These dialogs sometimes appear on Gradle Managed Devices and would break<br> * our tests. Better to dismiss them proactively.<br> */<br>internal fun MacrobenchmarkScope.dismissSystemAlert() {<br>    try {<br>        // Look for &quot;Close&quot; button on system error dialogs (regex pattern)<br>        if (device.wait(Until.hasObject(By.res(&quot;.*aerr_close&quot;)), 1000)) {<br>            device.findObject(By.res(&quot;.*aerr_close&quot;)).click()<br>            device.waitForIdle()<br>        }<br>    } catch (e: Throwable) {<br>        // Dialog not present? No problem, continue<br>    }<br>}<br><br>/**<br> * Ensures the app is fully loaded and ready for interaction by checking for<br> * system dialogs and waiting for UI stability. <br> * <br> * Call this after major navigation or app restarts.<br> */<br>internal fun MacrobenchmarkScope.ensureAppReady() {<br>    dismissSystemAlert()        // Check for dialogs<br>    device.waitForIdle(5000)    // Wait 5 seconds for animations/loading<br>    dismissSystemAlert()        // Check again (some dialogs appear late!)<br>}<br><br>/**<br> * Automated sign-in flow for testing.<br> * <br> * This simulates a user going through the entire onboarding:<br> * phone input → OTP → email → home screen<br> * <br> * We use a reserved test account (9999999999) that works in QA/staging<br> * environments.<br> */<br>internal fun MacrobenchmarkScope.signIn() {<br>    device.waitForIdle()<br>    dismissSystemAlert()<br>    <br>    // Step 1: Click &quot;Get Started&quot; button on landing screen<br>    device.waitAndFindObject(By.res(packageName, &quot;btn_get_started&quot;)).click()<br>    <br>    // Step 2: Enter test phone number<br>    val phoneInput = device.waitAndFindObject(<br>        By.res(getApplicationPackageToTest(), &quot;et_phone_number&quot;)  // Find EditText by resource ID<br>    )<br>    phoneInput.text = &quot;9999999999&quot;  // Reserved test number (never expires)<br>    <br>    // Step 3: Accept terms and conditions checkbox<br>    device.waitAndFindObject(By.res(packageName, &quot;cb_accept_terms&quot;)).click()<br>    <br>    // Step 4: Continue with OTP flow...<br>    // In a real implementation, you&#39;d:<br>    // - Click &quot;Next&quot; button<br>    // - Enter OTP (000000 works in test environments)<br>    // - Wait for email verification screen<br>    // - Skip optional steps<br>    // - Wait for home screen to appear<br>    // (Additional steps omitted for brevity)<br>    <br>    // Step 5: Wait for login to complete<br>    device.waitForIdle(45000)  // Can take ~30-45 seconds to fetch user data<br>}<br><br>/**<br> * Returns the package name of the app under test.<br> * Useful for finding UI elements by resource ID.<br> */<br>fun getApplicationPackageToTest() = &quot;com.example.fintech&quot;<br>```</pre><p><strong>What’s happening in <em>signIn()</em>?</strong></p><p>This function automates your entire onboarding flow. Here’s why this is useful:<br>1. <em>You need a logged-in user </em>to profile the home screen/features<br>2. <em>You don’t want to profile the login flow </em>itself (that’s a separate generator!)<br>3. <em>You run this once</em> (iteration 1), then skip it in iterations 2–5</p><p><em>Finding UI elements</em>: We use <em>By.res(packageName, “id”)</em> to find elements by resource ID (most reliable), or <em>By.desc()</em> for accessibility descriptions.</p><p><em>Common Pitfall</em>: Hardcoded waits like <em>Thread.sleep(5000)</em>. Don’t! Use <em>device.waitForIdle()</em> or <em>waitAndFindObject()</em> instead. They’re smarter — they continue as soon as the UI is ready, not after an arbitrary delay.</p><p><strong>🎉 You now have a complete toolkit!</strong> With these helpers, writing new profile generators becomes much faster. Just extend <em>BaselineProfileGeneratorScaffold</em>, use the helpers, and focus on your user journey.</p><p><strong>Running Profile Generation</strong></p><p>Alright, you’ve written your profile generator. Now let’s actually run it and generate those magical profile files!</p><p><strong>Option 1: Gradle Managed Device (Recommended for CI/CD)</strong></p><pre># Run a specific profile generator<br>./gradlew :baselineprofile:pixel6Api34QaReleaseAndroidTest \<br>  -Pandroid.testInstrumentationRunnerArguments.class=com.example.fintech.baselineprofile.profilegen.HomeQrProfileGenerator</pre><p><strong>What happens:</strong> Gradle downloads an Android emulator image, spins it up, installs your app, runs the generator 5 times, collects data, and generates the profile files. Takes about 10–15 minutes.</p><p><strong>Pros</strong>: Reproducible, works in CI/CD, no physical device needed<br><strong>Cons</strong>: Slower than real devices, sometimes flaky</p><p><strong>Option 2: Generate All Profiles at Once</strong></p><pre># This runs ALL your profile generators (if you have multiple)<br>./gradlew :app:generateQaReleaseBaselineProfile</pre><p><strong>What happens:</strong> Same as above, but runs every <em>ProfileGenerator</em> class you’ve created.<br><strong>When to use</strong>: After you’ve tested individual generators and want the complete profile set.</p><p><strong>Option 3: Connected Physical Device (Best for Final Profiles)</strong></p><pre># Connect your phone via USB with ADB debugging enabled<br>adb devices  # Verify it&#39;s connected<br><br># Run on the connected device<br>./gradlew :baselineprofile:connectedQaReleaseAndroidTest</pre><p><strong>What happens</strong>: Runs on your actual phone. Faster and more representative of real user performance.<br><strong>Pros</strong>: Most accurate, faster, fewer flakes<br><strong>Cons</strong>: Requires physical device, can’t automate in CI/CD easily</p><p><strong>What will you get?</strong></p><p>After generation completes (grab a coffee, it takes time!), you’ll find two files in <em>app/src/main/generated/baselineProfiles/</em>:</p><p>1. <strong>baseline-prof.txt<br></strong>- Contains ALL profiled methods from your test<br>- Typically 50,000–100,000+ lines in a production app<br>- Includes methods with H, S, P, and L flags</p><p>2. <strong>startup-prof.txt<br></strong>- Contains ONLY startup-critical methods (those with S flag)<br>- Smaller subset of baseline-prof.txt<br>- These get highest compilation priority</p><p><strong>Important:</strong> These files are <em>automatically included </em>in your APK/AAB when you build for release. You don’t need to do anything special — Gradle handles it!</p><pre># After generation, commit these files<br>git add app/src/main/generated/baselineProfiles/<br>git commit -m &quot;feat: add baseline profiles for home and QR flows&quot;</pre><p><strong>Debugging Failed Generations</strong></p><p><strong>Test hangs forever?<br></strong>- Check if your <em>waitAndFindObject()</em> timeout is too long<br>- Increase logging: Add more <em>Log.i()</em> statements<br>- Enable emulator display: Set e<em>nableEmulatorDisplay = true</em> in baselineprofile.gradle.kts</p><p><strong>“Element not found” errors?<br>-</strong> Your UI element might not have a <em>contentDescription</em> or <em>testTag</em><br>- The screen might not be loading (network issue?)<br>- Add logging to see what’s on screen: <em>Log.d(TAG, device.windowHierarchyToString())</em></p><p><strong>Test passes but files not generated?<br></strong>- Check the build output: <em>app/src/qaRelease/generated/baselineProfiles/</em> (variant-specific)<br>- You might need to move them to <em>src/main/</em> manually (or use the copy task we configured earlier)</p><h3>Benchmarking: Measuring What Matters</h3><p>Generating profiles is only half the story. You need to <strong>measure </strong>the impact to know if they’re working.</p><p><strong>Why Benchmark?</strong></p><p>- 📊 <strong>Quantify improvements</strong>: “30% faster” beats “feels faster”<br>- 🐛 <strong>Catch regressions</strong>: Know immediately if a code change hurts performance<br>- 🎯 <strong>Prioritize optimizations</strong>: Focus on what actually matters</p><p><strong>Creating Benchmark Tests</strong></p><p>Macrobenchmark tests measure real-world user-facing metrics. Here’s a complete example:</p><pre>package com.example.fintech.baselineprofile.benchmarks<br><br>import android.content.Intent<br>import androidx.benchmark.macro.BaselineProfileMode<br>import androidx.benchmark.macro.CompilationMode<br>import androidx.benchmark.macro.StartupMode<br>import androidx.benchmark.macro.StartupTimingMetric<br>import androidx.benchmark.macro.junit4.MacrobenchmarkRule<br>import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner<br>import org.junit.Rule<br>import org.junit.Test<br>import org.junit.runner.RunWith<br><br>/**<br> * This benchmark measures app startup performance.<br> * It compares performance with and without Baseline Profiles.<br> */<br>@RunWith(AndroidJUnit4ClassRunner::class)<br>class ColdStartupBenchmark {<br><br>    @get:Rule<br>    val rule = MacrobenchmarkRule()<br><br>    /**<br>     * Baseline: No optimization at all<br>     * This represents worst-case performance (fresh install without profiles)<br>     */<br>    @Test<br>    fun startupCompilationNone() = benchmark(CompilationMode.None())<br><br>    /**<br>     * With Baseline Profiles: Partial AOT compilation<br>     * This represents real user experience with profiles enabled<br>     */<br>    @Test<br>    fun startupPartialWithBaselineProfiles() =<br>        benchmark(CompilationMode.Partial(<br>            baselineProfileMode = BaselineProfileMode.Require<br>        ))<br><br>    /**<br>     * Best case: Full AOT compilation<br>     * Not representative of real users, but useful for comparison<br>     */<br>    @Test<br>    fun startupFullCompilation() = benchmark(CompilationMode.Full())<br><br>    private fun benchmark(compilationMode: CompilationMode) {<br>        rule.measureRepeated(<br>            packageName = &quot;com.example.fintech&quot;,<br>            metrics = listOf(StartupTimingMetric()),<br>            compilationMode = compilationMode,<br>            startupMode = StartupMode.COLD, // Fresh start every iteration<br>            iterations = 15, // Run 15 times for statistical significance<br>            setupBlock = {<br>                killProcess() // Ensure cold start<br>                device.waitForIdle()<br>                pressHome()<br>            },<br>            measureBlock = {<br>                // Start the app and measure time to fully drawn<br>                startActivityAndWait(Intent().apply {<br>                    setClassName(<br>                        &quot;com.example.fintech&quot;,<br>                        &quot;com.example.fintech.ui.LauncherActivity&quot;<br>                    )<br>                })<br>                // Measurements automatically captured here<br>            }<br>        )<br>    }<br>}</pre><p><strong>Benchmark: Home Screen User Journey</strong></p><p>Let’s benchmark a more complex flow- navigating to home and interacting with it:</p><pre>package com.example.fintech.baselineprofile.benchmarks<br><br>import android.content.Intent<br>import androidx.benchmark.macro.BaselineProfileMode<br>import androidx.benchmark.macro.CompilationMode<br>import androidx.benchmark.macro.StartupTimingMetric<br>import androidx.benchmark.macro.junit4.MacrobenchmarkRule<br>import androidx.test.uiautomator.By<br>import androidx.test.uiautomator.Direction<br>import org.junit.Rule<br>import org.junit.Test<br>import org.junit.runner.RunWith<br>import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner<br>import java.util.regex.Pattern<br><br>private var isSignupDone = false<br><br>@RunWith(AndroidJUnit4ClassRunner::class)<br>class HomeStartupBenchmarks {<br><br>    @get:Rule<br>    val rule = MacrobenchmarkRule()<br><br>    @Test<br>    fun startupCompilationNone() = benchmark(CompilationMode.None())<br><br>    @Test<br>    fun startupPartialWithBaselineProfiles() =<br>        benchmark(CompilationMode.Partial(<br>            baselineProfileMode = BaselineProfileMode.Require<br>        ))<br><br>    @Test<br>    fun startupFullCompilation() = benchmark(CompilationMode.Full())<br><br>    private fun benchmark(compilationMode: CompilationMode) {<br>        rule.measureRepeated(<br>            packageName = &quot;com.example.fintech&quot;,<br>            metrics = listOf(StartupTimingMetric()),<br>            compilationMode = compilationMode,<br>            iterations = 15,<br>            setupBlock = {<br>                pressHome()<br>                if (!isSignupDone) {<br>                    isSignupDone = true<br>                    allowPermissions() // Don&#39;t measure permission flow<br>                    setPin()<br>                    signIn() // Get user logged in<br>                }<br>            },<br>            measureBlock = {<br>                // Measure time to launch and interact with home<br>                startActivityAndWait(Intent().apply {<br>                    setClassName(<br>                        &quot;com.example.fintech&quot;,<br>                        &quot;com.example.fintech.ui.LauncherActivity&quot;<br>                    )<br>                })<br>                device.waitForIdle()<br>                <br>                // Find main scroll view and scroll to trigger lazy loading<br>                val mainScrollView = device.waitAndFindObject(<br>                    By.res(Pattern.compile(&quot;.*main_scrollview.*&quot;))<br>                )<br>                mainScrollView.scroll(Direction.UP, 1f)<br>                mainScrollView.scroll(Direction.DOWN, 1f)<br>                device.waitForIdle()<br>                <br>                // This measures the complete home screen load + scroll performance<br>            }<br>        )<br>    }<br>}</pre><p><strong>Running Benchmarks</strong></p><p>Execute benchmarks on a physical device (emulators give unrealistic results):</p><pre># Run specific benchmark<br>./gradlew :baselineprofile:connectedBaselineprofAndroidTest \<br>  -Pandroid.testInstrumentationRunnerArguments.class=com.example.fintech.baselineprofile.benchmarks.ColdStartupBenchmark<br><br># Run all benchmarks<br>./gradlew :baselineprofile:connectedBaselineprofAndroidTest<br><br># View results in Android Studio or in terminal output</pre><p><strong>Understanding Benchmark Results</strong></p><p>You’ll get output like this:</p><pre>ColdStartupBenchmark_startupCompilationNone<br>  timeToInitialDisplayMs   min 841.2,   median 872.4,   max 924.1<br>  timeToFullDisplayMs      min 1524.8,  median 1587.3,  max 1654.2<br><br>ColdStartupBenchmark_startupPartialWithBaselineProfiles<br>  timeToInitialDisplayMs   min 521.3,   median 548.7,   max 592.1<br>  timeToFullDisplayMs      min 892.4,   median 934.2,   max 1012.8</pre><p><strong>Analysis:</strong><br>- <em>Without profiles</em>: ~872ms to initial display, ~1587ms to fully drawn<br>- <em>With profiles</em>: ~549ms to initial display, ~934ms to fully drawn<br>- <em>Improvement</em>: ~37% faster startup! 🚀</p><h3><strong>Behind the Scenes: How Baseline Profiles Are Generated</strong></h3><p>Now that you’ve seen how to generate and benchmark profiles, let’s dive into what actually happens under the hood. Remember those mysterious <strong>HSPL</strong> prefixes in the profile files? Let’s understand how Android decides which methods get which flags.</p><p><strong>Understanding the HSPL Flags</strong></p><p>Each letter represents a characteristic that Android’s profiling system observes during your test execution:</p><figure><img alt="what each - H,S,P, L tell the Android Runtime" src="https://cdn-images-1.medium.com/max/1024/1*QG_HfXy38y8l_fkF5Aa0Rg.jpeg" /></figure><p>Methods can have <strong>multiple flags</strong> combined. For example:</p><p>HSPLandroidx/activity/ComponentActivity;-&gt;onCreate(Landroid/os/Bundle;)V</p><p>This has <strong>H+S+P+L</strong> because it’s:<br>- Called frequently (H)<br>- Critical for startup (S)<br>- Also used post-startup when opening new activities (P)<br>- Contains internal loops in initialization logic (L)</p><p><strong>The Profile Generation Process</strong></p><p>When you run:</p><pre>./gradlew :app:generateQaReleaseBaselineProfile</pre><p>Here’s what happens step by step:</p><p><strong>Step 1: Test Execution</strong></p><p>Your MacrobenchmarkScope.profileBlock() runs<br> ↓<br>Android Runtime (ART) monitors execution<br> ↓<br>Every method call is tracked with metadata:<br>- When was it called? (timestamp)<br>- How many times? (invocation count)<br>- What phase? (startup vs post-startup)<br>- Does it have loops? (bytecode analysis)</p><p><strong>Step 2: Data Collection</strong></p><p>During your test iterations (typically 5–10 runs), ART collects:</p><pre>// Pseudocode of what ART tracks internally<br>data class MethodProfile(<br>    val signature: String,<br>    val invocationCount: Int,<br>    val calledDuringStartup: Boolean,<br>    val calledPostStartup: Boolean,<br>    val hasLoops: Boolean,<br>    val hotnesScore: Float<br>)</pre><p><strong>Step 3: Flag Assignment</strong></p><p>After all iterations complete, ART analyzes the data:</p><pre>// Simplified algorithm of how flags are determined<br>fun determineFlags(method: MethodProfile): String {<br>    var flags = &quot;&quot;<br>    <br>    // Hot method check (high invocation count)<br>    if (method.invocationCount &gt; HOT_THRESHOLD) {  // e.g., &gt; 100 calls<br>        flags += &quot;H&quot;<br>    }<br>    <br>    // Startup critical check<br>    if (method.calledDuringStartup) {<br>        flags += &quot;S&quot;  // Called before Activity.reportFullyDrawn()<br>    }<br>    <br>    // Post-startup check<br>    if (method.calledPostStartup) {<br>        flags += &quot;P&quot;  // Called after fully drawn<br>    }<br>    <br>    // Loop check (bytecode analysis)<br>    if (method.hasLoops) {<br>        flags += &quot;L&quot;  // Contains loop constructs<br>    }<br>    <br>    return flags<br>}</pre><p><strong>Step 4: File Generation</strong></p><p>Two files are generated:<br>1. <em>startup-prof.txt</em> — Only methods with S flag (startup-critical)<br>2. <em>baseline-prof.txt — </em>All profiled methods (S + P)</p><p><strong>Real Example Walkthrough</strong></p><p>Let’s trace a real scenario from our profile generator:</p><pre>class HomeQrProfileGenerator : BaselineProfileGeneratorScaffold() {<br>    override fun shouldIncludeInStartupProfile(): Boolean = true<br>    <br>    override fun MacrobenchmarkScope.profileBlock() {<br>        // 1. Launch app<br>        startActivityAndWait(Intent().apply {<br>            setClassName(packageName, &quot;LauncherActivity&quot;)<br>        })<br>        <br>        // 2. Wait for home screen<br>        device.waitForIdle()<br>        <br>        // 3. Click primary button<br>        device.findObject(By.res(packageName, &quot;qr_button&quot;)).click()<br>    }<br>}</pre><p><strong>What gets profiled?</strong></p><pre>Timeline of execution:<br><br>T=0ms:    startActivityAndWait() called<br>T=50ms:   ├─ ComponentActivity.&lt;init&gt;()      → Called once, startup phase<br>          ├─ ComponentActivity.onCreate()     → Called once, startup phase<br>          └─ LifecycleRegistry.handleEvent()  → Called 3 times, startup phase<br><br>T=150ms:  LauncherActivity.onCreate() called       → Called once, startup phase<br>          ├─ initializeDependencies()         → Called once, has loops<br>          └─ setupUI()                        → Called once, startup phase<br><br>T=300ms:  DashboardScreen composable recomposes    → Called 12 times (Hot!), startup<br>          └─ ContentCard composable            → Called 4 times, startup<br><br>T=500ms:  reportFullyDrawn() called           ← Startup phase ENDS here<br><br>T=600ms:  User clicks FAB<br>T=650ms:  FeatureScreen shown                 → Called once, POST-startup</pre><p><strong>Resulting flags:</strong></p><pre>HSPLandroidx/activity/ComponentActivity;-&gt;onCreate(...)<br>  → H (called often across iterations)<br>  → S (called during startup)<br>  → P (also used when opening new activities post-startup)<br>  → L (contains loops)<br><br>PLcom/example/fintech/ui/LauncherActivity;-&gt;initializeDependencies(...)<br>  → P (happens post-splash, not critical startup)<br>  → L (has loops iterating through dependencies)<br>  → No H (only called once)<br>  → No S (not in critical startup path)<br><br>HSPLcom/example/fintech/home/DashboardScreen;-&gt;DashboardScreenContent(...)<br>  → H (recomposes frequently due to state changes)<br>  → S (visible at startup)<br>  → P (also recomposes post-startup)<br>  → L (contains LazyColumn loops)</pre><p><strong>How does <em>includeInStartupProfile</em> Affects Flags?</strong></p><p>This flag controls which profile file methods appear in:</p><pre>// When TRUE:<br>override fun shouldIncludeInStartupProfile(): Boolean = true</pre><p>- Methods get S flag if called during your test<br>- They appear in <em>startup-prof.txt</em><br>- ART compiles them <em>immediately on app install</em><br>- Use for: App launch, splash, home screen</p><pre>// When FALSE:<br>override fun shouldIncludeInStartupProfile(): Boolean = false</pre><p>- Methods get P flag instead of S<br>- They appear only in <em>baseline-prof.txt</em>, not startup-prof.txt<br>- ART compiles them <em>with lower priority</em><br>- Use for: Configuration, user screens, less-critical flows</p><p><strong>Why Does This Matters for Optimization?</strong></p><p>The flags tell ART how aggressively to optimize:</p><p>Compilation Priority:</p><p>HS methods (startup + hot)<br> ↓ Highest priority — compile FIRST with full optimizations<br>H methods (hot only)<br> ↓ High priority — compile early<br>S methods (startup only)<br> ↓ Medium-high — compile before first launch<br>P methods (post-startup)<br> ↓ Lower priority — compile in background<br>L methods (loops)<br> ↓ Special optimizations: loop unrolling, vectorization</p><p><strong>Performance Impact:<br></strong>- HS methods: Optimized before app launch = instant fast execution<br>- P methods: Optimized in background = minimal startup impact<br>- L methods: Loop optimizations = up to 10x faster iteration</p><p><strong>Viewing the Generation Process</strong></p><p>Want to see what’s happening in real-time? Run with verbose logging:</p><pre># Verbose output<br>./gradlew :app:generateQaReleaseBaselineProfile --info<br><br># You&#39;ll see:<br># ✓ Starting profile generation...<br># ✓ Iteration 1/5: Collected 3,421 method samples<br># ✓ Iteration 2/5: Collected 3,398 method samples<br># ✓ Iteration 3/5: Collected 3,415 method samples<br># ✓ Iteration 4/5: Collected 3,407 method samples<br># ✓ Iteration 5/5: Collected 3,411 method samples<br># <br># Aggregating results...<br># ├─ Startup methods: 1,234<br># ├─ Post-startup methods: 2,187<br># ├─ Hot methods: 876<br># └─ Methods with loops: 543<br>#<br># ✓ Generated: baseline-prof.txt (88,639 methods)<br># ✓ Generated: startup-prof.txt (1,234 methods)</pre><p><strong>Advanced: Analyzing Profiling Data</strong></p><pre>override fun MacrobenchmarkScope.profileBlock() {<br>    // Start trace<br>    device.executeShellCommand(&quot;cmd simpleperf record -a --duration 30&quot;)<br>    <br>    // Your user journey<br>    startActivityAndWait(...)<br>    <br>    // Trace shows EXACTLY when each method was called<br>    // Pull the trace file and analyze in Android Studio Profiler<br>}</pre><p>Then use <em>Android Studio Profiler</em> or <em>Perfetto</em> to visualize:<br>- Exact call stacks<br>- Method invocation counts<br>- Timing information<br>- Why specific flags were assigned</p><p><strong>Key Takeaways</strong></p><ul><li>You don’t manually write HSPL flags - They’re auto-generated</li><li>Flags are based on actual runtime behavior during your test</li><li>More realistic user journeys = better flag assignments</li><li>Multiple test iterations (5–10) produce more accurate flags</li><li>includeInStartupProfile controls S vs P flag assignment</li></ul><p><strong>Best Practices for Better Profiles</strong></p><ul><li>Run tests on real devices - Emulators have different performance characteristics</li><li>Use representative user journeys - Profile what users actually do</li><li>Multiple iterations matter - Don’t skip iterations, they improve accuracy</li><li>Don’t over-profile - Only profile critical flows (startup, main features)</li><li>Re-generate regularly - After major code changes, regenerate profiles</li></ul><h3>Real-World Results</h3><p>Let’s look at what a production Baseline Profile looks like and the improvements it brings.</p><p><strong>Profile File Structure</strong></p><p>A generated <em>startup-prof.txt</em> contains thousands of entries:</p><pre># Coroutines initialization (hot paths marked with HSP)<br>HSPLkotlinx/coroutines/CoroutineDispatcher;-&gt;&lt;init&gt;()V<br>HSPLkotlinx/coroutines/Dispatchers;-&gt;getMain()Lkotlinx/coroutines/MainCoroutineDispatcher;<br><br># Activity lifecycle (critical startup path)<br>HSPLandroidx/activity/ComponentActivity;-&gt;&lt;init&gt;()V<br>HSPLandroidx/activity/ComponentActivity;-&gt;onCreate(Landroid/os/Bundle;)V<br>HSPLandroidx/activity/ComponentActivity;-&gt;getLifecycle()Landroidx/lifecycle/Lifecycle;<br><br># Jetpack Compose initialization<br>HSPLandroidx/compose/runtime/Composer;-&gt;startRestartGroup(I)Landroidx/compose/runtime/Composer;<br>HSPLandroidx/compose/ui/platform/ComposeView;-&gt;setContent(Lkotlin/jvm/functions/Function2;)V<br><br># Your app&#39;s LauncherActivity<br>PLcom/example/fintech/ui/LauncherActivity;-&gt;onCreate(Landroid/os/Bundle;)V<br>PLcom/example/fintech/ui/LauncherActivity;-&gt;initializeDependencies()V<br><br># Home screen composables<br>HSPLcom/example/fintech/home/DashboardScreen;-&gt;DashboardScreenContent(Landroidx/compose/runtime/Composer;I)V<br>PLcom/example/fintech/home/components/ContentCard;-&gt;ContentCard(Landroidx/compose/runtime/Composer;I)V</pre><p>Each entry represents a method that will be compiled before the user launches your app.</p><p><strong>File Statistics</strong></p><p>In a typical production app:<br>- <em>baseline-prof.txt</em>: 88,639 lines (all profiled code paths)<br>- <em>startup-prof.txt</em>: 88,659 lines (startup-critical paths)<br>- <em>File size</em>: ~5–8MB (before compilation, not shipped to users)<br>- <em>APK size increase</em>: ~1–2MB (the compiled code)</p><p><strong>Performance Improvements Observed</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQ3GgtTboow_rYIl1ajP9A.jpeg" /></figure><p><strong>APK Size Impact<br></strong>APK without Baseline Profiles: 45.2 MB<br>APK with Baseline Profiles: 46.8 MB<br>Increase: 1.6 MB (3.5%)</p><p><strong>Trade-off</strong>: Slightly larger APK for significantly better user experience. Worth it!</p><h3>Best Practices and Tips</h3><p>✅ DO: Profile Critical User Journeys</p><p>Focus on the flows users take most often:<br>- App launch<br>- Login/authentication<br>- Main screen load<br>- Primary features (search, checkout, etc.)</p><pre>class TransactionFlowProfileGenerator : BaselineProfileGeneratorScaffold() {<br>    override fun shouldIncludeInStartupProfile() = false // Not startup-critical<br>    <br>    override fun MacrobenchmarkScope.profileBlock() {<br>        navigateToSection()<br>        proceedToNext()<br>        enterTransactionDetails()<br>        confirmAction()<br>    }<br>}</pre><p>✅ DO: Keep Startup Profiles Lean</p><p>Only mark flows as startup-critical if they’re <em>immediately visible</em> after launch:</p><pre>// ✅ GOOD: Home screen is shown immediately<br>class DashboardProfileGenerator : BaselineProfileGeneratorScaffold() {<br>    override fun shouldIncludeInStartupProfile() = true<br>}<br><br>// ❌ BAD: Configuration screens are not shown at startup<br>class ConfigurationProfileGenerator : BaselineProfileGeneratorScaffold() {<br>    override fun shouldIncludeInStartupProfile() = false // Correct!<br>}</pre><p>✅ DO: Run Benchmarks on Physical Devices</p><pre># ✅ GOOD: Use a real device<br>./gradlew :baselineprofile:connectedBaselineprofAndroidTest<br><br># ❌ BAD: Emulator results are not representative<br>./gradlew :baselineprofile:pixel6Api34BaselineprofAndroidTest</pre><p>Emulators share CPU with your computer and don’t represent real-world performance.</p><p>✅ DO: Disable Battery Optimizations</p><p>Before running benchmarks:</p><pre>adb shell settings put global stay_on_while_plugged_in 7<br>adb shell dumpsys battery unplug<br>adb shell dumpsys deviceidle disable</pre><p>Or manually: Device Settings → Battery → Battery optimization → Your app → Don’t optimize</p><p>✅ DO: Update Profiles Regularly</p><p>Regenerate profiles:<br>- After major feature additions<br>- When you refactor critical paths<br>- Every 2–3 releases</p><pre># Automate in CI/CD<br>./gradlew :app:generateProdReleaseBaselineProfile<br>git add app/src/main/generated/baselineProfiles/<br>git commit -m &quot;chore: update baseline profiles&quot;</pre><p>❌ DON’T: Profile Everything</p><p>More isn’t always better. Over-profiling:<br>- Increases APK size unnecessarily<br>- May not improve startup (if methods aren’t called)<br>- Wastes compilation time</p><pre>// ❌ BAD: Profiling rarely-used settings<br>class RareFeatureProfileGenerator : BaselineProfileGeneratorScaffold() {<br>    override fun shouldIncludeInStartupProfile() = true // Wasteful!<br>}</pre><p>### ❌ DON’T: Forget ProGuard Consideration</p><p>Baseline Profiles work <em>after</em> ProGuard obfuscation. Make sure your benchmark build type has similar ProGuard rules to release:</p><pre>// app/build.gradle.kts<br>buildTypes {<br>    create(&quot;baselineprof&quot;) {<br>        initWith(getByName(&quot;release&quot;))<br>        signingConfig = signingConfigs.getByName(&quot;debug&quot;) // Debug signing for easier testing<br>        proguardFiles(&quot;benchmark-rules.pro&quot;) // Lighter rules, but still representative<br>    }<br>}</pre><p>### ❌ DON’T: Run Benchmarks Without Warming Up</p><p>Always include proper setup:</p><pre>private fun benchmark(compilationMode: CompilationMode) {<br>    rule.measureRepeated(<br>        // ...<br>        setupBlock = {<br>            // ✅ GOOD: Clean state before measurement<br>            pressHome()<br>            killProcess()<br>            device.waitForIdle()<br>        },<br>        measureBlock = {<br>            // Measurement happens here<br>        }<br>    )<br>}</pre><h3><strong>Conclusion</strong></h3><p>Baseline Profiles are a <strong>low-effort, high-impact</strong> optimization that every Android app should implement. With just a few hours of setup, you can achieve:</p><p>- 🚀 30–40% faster app startup<br>- ✨ Smoother user experience<br>- 📱 Better performance on low-end devices<br>- 💚 Happier users and better retention</p><p>The key takeaways:<br>1. <strong>Set up once</strong>: Create a baseline profile module<br>2. <strong>Profile smart</strong>: Focus on critical user journeys<br>3. <strong>Measure always</strong>: Use benchmarks to verify improvements<br>4. <strong>Update regularly</strong>: Keep profiles in sync with your app</p><p>Start with app startup, then expand to your most important features. Your users will thank you!</p><p><strong>Resources<br>- </strong><a href="https://developer.android.com/topic/performance/baselineprofiles">Official Android Documentation</a><br>- <a href="https://developer.android.com/topic/performance/benchmarking/macrobenchmark-overview">Macrobenchmark Guide</a><br>- <a href="https://developer.android.com/develop/ui/compose/performance">Jetpack Compose Performance</a><br>- <a href="https://www.youtube.com/@PhilippLackner">Philip Lackner’s YouTube</a> - Excellent Android tutorials</p><p><strong>Appendix: Complete Code Repository Structure</strong></p><pre>android-project/<br>├── app/<br>│   ├── src/<br>│   │   └── main/<br>│   │       └── generated/<br>│   │           └── baselineProfiles/<br>│   │               ├── baseline-prof.txt (generated)<br>│   │               └── startup-prof.txt (generated)<br>│   └── app.gradle.kts (with baseline profile plugin)<br>│<br>├── baselineprofile/<br>│   ├── src/<br>│   │   └── main/<br>│   │       └── java/com/example/fintech/baselineprofile/<br>│   │           ├── benchmarks/<br>│   │           │   ├── StartupBenchmarks.kt<br>│   │           │   ├── HomeStartupBenchmarks.kt<br>│   │           │   └── HomeFeatureStartupBenchmarks.kt<br>│   │           ├── profilegen/<br>│   │           │   ├── BaselineProfileGeneratorScaffold.kt<br>│   │           │   └── HomeQrProfileGenerator.kt<br>│   │           ├── CommonExtensions.kt<br>│   │           ├── CommonUserFlows.kt<br>│   │           └── Constants.kt<br>│   └── baselineprofile.gradle.kts<br>│<br>└── settings.gradle.kts (includes baselineprofile module)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74b9c6c0d71c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST vs gRPC- detailed explanation with a simple example]]></title>
            <link>https://medium.com/@sneha_71656/rest-vs-grpc-explained-with-a-simple-example-6a7e8cf76315?source=rss-84e4a9435d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a7e8cf76315</guid>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sneha]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 01:32:01 GMT</pubDate>
            <atom:updated>2025-10-27T01:57:08.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NScpnurtTNEjw0m1G7LGA.png" /></figure><p><em>-Authored by an android developer who has implemented both in production systems</em></p><h3>Introduction</h3><p>As developers, we often hear &quot;<strong>REST</strong>&quot; and &quot;<strong>gRPC</strong>&quot; thrown around in architecture discussions. Both are ways for clients and servers to talk, but they work fundamentally differently. Today, I&#39;ll show you exactly what happens under the hood when your code makes an API call.</p><p>Let&#39;s use a simple example: <strong>Getting a user&#39;s profile information</strong>. This is something every app needs, so it&#39;s perfect for comparison.</p><h3>Our Example: Getting User Profile</h3><p><strong>API Purpose</strong>: Fetch user details like name, email, and profile picture<br><strong>Endpoint</strong>: getUserProfile(userId)<br><strong>Input</strong>: User ID<br><strong>Output</strong>: User&#39;s full profile information</p><p>Now, let&#39;s see how this exact same functionality works with REST and gRPC.</p><h3>Part 1: REST API - The Familiar Friend</h3><h3>How REST Works</h3><p>REST (Representational State Transfer) uses <strong>HTTP</strong> - the same protocol your browser uses. It&#39;s simple, human-readable, and has been around since the early 2000s.</p><h4>The Client Code (Kotlin/Retrofit Example)</h4><p>1. Define the API interface</p><pre>interface UserApi {<br> @GET(&quot;/api/v1/users/{userId}/profile&quot;)<br> suspend fun getUserProfile(@Path(&quot;userId&quot;) userId: String): Response&lt;UserProfile&gt;<br>}</pre><p>2. Create the data model</p><pre>data class UserProfile(<br> val id: String,<br> val name: String,<br> val email: String,<br> val profilePicture: String<br>)</pre><p>3. Call it</p><pre>val profile = apiService.getUserProfile(&quot;user123&quot;)</pre><h4>Step-by-Step: What Happens Over the Network</h4><p><strong>1. Client Sends the Request</strong></p><p>Your code calls the function. Retrofit (or your HTTP client) constructs an HTTP request:</p><pre>GET /api/v1/users/user123/profile HTTP/1.1<br>Host: api.myapp.com<br>Accept: application/json<br>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...<br>Content-Type: application/json<br>User-Agent: MyApp/1.0 (Android)</pre><p><strong>What this looks like on the wire:<br>- Protocol</strong>: HTTP/1.1 (or HTTP/2 if supported)<br>- <strong>Format</strong>: Plain text HTTP headers<br>- <strong>Method</strong>: GET<br>- <strong>Path</strong>: <em>/api/v1/users/user123/profile</em></p><p>The actual network transmission is human-readable:</p><pre>HTTP REQUEST:<br>00000000: 47 45 54 20 2f 61 70 69  2f 76 31 2f 75 73 65 72   GET /api/v1/user<br>00000010: 73 2f 75 73 65 72 31 32  33 2f 70 72 6f 66 69 6c   s/user123/profil<br>00000020: 65 20 48 54 54 50 2f 31  2e 31 0d 0a 48 6f 73 74   e HTTP/1.1..Host<br>00000030: 3a 20 61 70 69 2e 6d 79  61 70 70 2e 63 6f 6d 0d   : api.myapp.com.<br>00000040: 0a 41 63 63 65 70 74 3a  20 61 70 70 6c 69 63 61   .Accept: applica<br>00000050: 74 69 6f 6e 2f 6a 73 6f  6e 0d 0a 0d 0a            tion/json....</pre><p><strong>2. Server Processes and Responds</strong></p><p>The server receives your request, looks up the user, and sends back JSON:</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br>Content-Length: 156<br>Cache-Control: no-cache<br><br>{<br>&quot;id&quot;: &quot;user123&quot;,<br>&quot;name&quot;: &quot;John Doe&quot;,<br>&quot;email&quot;: &quot;john.doe@example.com&quot;,<br>&quot;profilePicture&quot;: &quot;https://cdn.myapp.com/users/123/profile.jpg&quot;<br>}</pre><p><strong>Size on wire</strong>: ~300 bytes (headers + JSON)</p><p><strong>3. Client Receives and Parses</strong></p><p>Your HTTP client receives the response. Retrofit/Gson deserializes the JSON:</p><pre>UserProfile(<br> id = &quot;user123&quot;,<br> name = &quot;John Doe&quot;,<br> email = &quot;john.doe@example.com&quot;,<br> profilePicture = &quot;https://cdn.myapp.com/users/123/profile.jpg&quot;<br>)</pre><p>The entire flow is <strong>human-readable</strong>. You can literally open Network Inspector in Android Studio, see the request, and read the response as plain JSON.</p><h3>Part 2: gRPC - The Modern, Efficient Protocol</h3><h3>How gRPC Works</h3><p>gRPC (gRPC Remote Procedure Calls) uses <strong>Protocol Buffers</strong> (protobuf) - a binary serialization format. It&#39;s designed by Google for microservices communication and is much more efficient.</p><h4><strong>The Client Code (Kotlin/gRPC Example)</strong></h4><p>1. First, you define the API contract in a .proto file (think of it as an interface definition)</p><pre>// user_service.proto<br><br>syntax = &quot;proto3&quot;;<br><br>service UserService {<br>   rpc GetUserProfile(GetUserProfileRequest) returns (GetUserProfileResponse);<br>}<br><br>message GetUserProfileRequest {<br>   string user_id = 1;<br>}<br><br><br>message GetUserProfileResponse {<br>   string id = 1;<br>   string name = 2;<br>   string email = 3;<br>   string profile_picture = 4;<br>}</pre><p>2. gRPC generates client stubs for you.</p><p>Here’s where the magic happens! The gRPC <strong>protoc compiler</strong> (protocol buffer compiler) reads your <em>.proto</em> file and generates thousands of lines of Java/Kotlin code.</p><p><strong>What the compiler generates:</strong></p><p>1. <strong>Message Classes — </strong>Java classes for your data structures<br>2. <strong>Service Stubs —</strong> Ready-to-use client and server code<br>3. <strong>Serialization Code</strong> — Code to convert objects ↔ binary</p><p>Let me show you what actually gets generated:</p><p><strong>Generated: <em>GetUserProfileRequest.java</em></strong></p><pre>public static final class GetUserProfileRequest extends<br>com.google.protobuf.GeneratedMessageLite {<br>private java.lang.String userId_;<br>/**<br>* &lt;code&gt;string user_id = 1;&lt;/code&gt;<br>*/<br>@java.lang.Override<br>public java.lang.String getUserId() {<br>return userId_;<br>}<br>/**<br>* &lt;code&gt;string user_id = 1;&lt;/code&gt;<br>*/<br>public Builder setUserId(java.lang.String value) {<br>checkByteStringIsUtf8(value);<br>userId_ = value;<br>return this;<br>}<br>// … hundreds more lines of serialization code<br>}</pre><p><strong>Generated: <em>UserServiceGrpc.java</em> </strong><em>(The stub!)</em></p><pre>public final class UserServiceGrpc {<br>   public static final class UserServiceStub extends AbstractAsyncStub&lt;UserServiceStub&gt; {<br>      // This is what you call!<br>        public void getUserProfile(<br>           GetUserProfileRequest request,<br>           StreamObserver&lt;GetUserProfileResponse&gt; responseObserver) {<br>            // Ready-to-use network call code<br>            asyncUnaryCall(<br>                 getChannel().newCall(<br>                     getGetUserProfileMethod(),<br>                     getCallOptions()<br>                    ),<br>                 request,<br>                 responseObserver<br>            );<br>        }<br>  }<br><br>  // Blocking version for synchronous calls<br>  public static final class UserServiceBlockingStub extends AbstractBlockingStub&lt;UserServiceBlockingStub&gt; {<br>     public GetUserProfileResponse getUserProfile(GetUserProfileRequest request) {<br>        return blockingUnaryCall(<br>               getChannel(),<br>               getGetUserProfileMethod(),<br>               getCallOptions(),<br>               request<br>            );<br>        }<br>   }<br><br>   // Method descriptor - contains all the network routing info<br>   public static io.grpc.MethodDescriptor&lt;GetUserProfileRequest, GetUserProfileResponse&gt; getGetUserProfileMethod() {<br>      return MethodDescriptor.&lt;GetUserProfileRequest, GetUserProfileResponse&gt;newBuilder()<br>             .setType(MethodDescriptor.MethodType.UNARY)<br>               .setFullMethodName(<br>                   generateFullMethodName(<br>                           SERVICE_NAME,<br>                           &quot;GetUserProfile&quot;<br>                     )<br>              )<br>              .setRequestMarshaller(/* … */)<br>              .setResponseMarshaller(/* … */)<br>              .build();<br>    }<br>}</pre><p><strong>This generated code is ~5,000–10,000 lines!</strong> <br>It handles:<br>- Building/setting fields<br>- Serialization to binary<br>- Network routing<br>- Error handling<br>- HTTP/2 headers</p><p>3. Use the generated stub</p><pre>// Get the gRPC stub<br>val stub = UserServiceGrpc.newBlockingStub(channel)<br><br><br>// Make the call<br>val request = GetUserProfileRequest.newBuilder()<br>.setUserId(&quot;user123&quot;)<br>.build()<br><br>val response = stub.getUserProfile(request)<br>// response contains UserProfile data</pre><p><strong>That’s it!</strong> <br>The stub object you call is <strong>auto-generated</strong> and handles all the network plumbing.</p><h4>Why This is Different from REST ?</h4><p><strong>REST:<br></strong>- You manually write: API interface, call logic, JSON parsing, error handling<br>- ~100 lines of code you wrote</p><p><strong>gRPC:<br></strong>- You write: One `.proto` file (10 lines)<br>- Compiler generates: Thousands of lines of serialization/networking code<br>- You just call the generated stub<br>- ~10 lines of code you wrote</p><p>The stub is your “magic interface”— all the network stuff is already implemented!</p><h4>Step-by-Step: What Happens Over the Network</h4><p><strong>1. Client Sends the Request<br></strong>Your code calls the function. gRPC constructs the request:</p><pre>POST /UserService/GetUserProfile HTTP/2<br>Host: api.myapp.com:50051<br>Content-Type: application/grpc<br>grpc-encoding: identity<br>grpc-accept-encoding: gzip, identity<br>te: trailers<br>[Binary Protocol Buffer Data]</pre><p><strong>What this looks like on the wire:<br></strong>- <strong>Protocol</strong>: HTTP/2 (always)<br>- <strong>Format</strong>: <strong>Binary</strong> Protocol Buffer<br>- <strong>Method</strong>: POST (gRPC uses POST for all calls)<br>- <strong>Path</strong>:<em> /UserService/GetUserProfile</em></p><p>The actual network transmission is <strong>binary</strong> and <strong>not human-readable</strong>:</p><pre>HTTP REQUEST:<br>00000000: 50 4f 53 54 20 2f 55 73  65 72 53 65 72 76 69 63   POST /UserServic<br>00000010: 65 2f 47 65 74 55 73 65  72 50 72 6f 66 69 6c 65   e/GetUserProfil<br>00000020: 20 48 54 54 50 2f 32 0d  0a 48 6f 73 74 3a 20 61    HTTP/2..Host: a<br>00000030: 70 69 2e 6d 79 61 70 70  2e 63 6f 6d 0d 0a 0a      pi.myapp.com...<br><br>[BINARY PROTOBUF DATA]:<br>00000040: 0a 08 75 73 65 72 31 32  33                       ....user123</pre><p>The binary data <em>0a 08 75 73 65 72 31 32 33</em> means:<br>- <strong><em>0a — </em></strong>field tag for first field<br>- <strong><em>08</em></strong> — length of the string<br>- <strong><em>75 73 65 72 31 32 33 — </em></strong>&quot;user123&quot; in ASCII</p><p>This is <strong>much smaller</strong> than the REST version. The actual payload is just ~10 bytes!</p><p><strong>2. Server Processes and Responds</strong></p><p>The server receives your binary request, looks up the user, and sends back binary data:</p><pre>HTTP/2 200 OK<br>content-type: application/grpc<br>grpc-status: 0<br>[BINARY PROTOBUF DATA]</pre><p><strong>Response in binary:</strong></p><pre>00000000: 0a 08 75 73 65 72 31 32  33                        ...user123<br>00000009: 12 08 4a 6f 68 6e 20 44  6f 65                     ..John Doe<br>00000013: 1a 15 6a 6f 68 6e 2e 64  6f 65 40 65 78 61 6d 70   ..john.doe@examp<br>00000023: 6c 65 2e 63 6f 6d                                   le.com<br>00000029: 22 2a 68 74 74 70 73 3a  2f 2f 63 64 6e 2e 6d 79    &quot;*https://cdn.my<br>00000039: 61 70 70 2e 63 6f 6d 2f  75 73 65 72 73 2f 31 32    app.com/users/12<br>00000049: 33 2f 70 72 6f 66 69 6c  65 2e 6a 70 67              3/profile.jpg</pre><p><strong>Size on wire</strong>: ~80 bytes (vs 300 for REST!)</p><p><strong>3. Client Receives and Parses</strong></p><p>gRPC receives the binary stream and deserializes using the protobuf definitions:</p><pre>GetUserProfileResponse(<br> id = &quot;user123&quot;,<br> name = &quot;John Doe&quot;,<br> email = &quot;john.doe@example.com&quot;,<br> profilePicture = &quot;https://cdn.myapp.com/users/123/profile.jpg&quot;<br>)</pre><p>The gRPC client library automatically converts binary → objects for you.</p><h3>Side-by-Side Comparison</h3><p><strong>1. Network-Level Differences</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0xxBug4Wks1ejpNmceBCw.png" /></figure><p><strong>2. Request Size Comparison</strong></p><p><strong>REST Request:</strong></p><p>GET /api/v1/users/user123/profile HTTP/1.1<br>Headers: ~200 bytes<br>Body: none (it’s a GET)<br><em>Total: ~200 bytes</em></p><p><strong>gRPC Request:</strong></p><p>POST /UserService/GetUserProfile HTTP/2<br>Headers: ~150 bytes<br>Binary body: 10 bytes (just the userId)<br><em>Total: ~160 bytes</em></p><p><strong>3. Response Size Comparison</strong></p><p><strong>REST Response:</strong></p><p>HTTP/1.1 200 OK<br>Headers: ~150 bytes<br>JSON body: ~150 bytes<br><em>Total: ~300 bytes</em></p><p><strong>gRPC Response:</strong></p><p>HTTP/2 200 OK<br>Headers: ~100 bytes<br>Binary body: ~60 bytes<br><em>Total: ~160 bytes</em></p><blockquote><strong>gRPC is ~50% smaller </strong>even for this simple example!</blockquote><h4>Deep Dive: What’s Actually Transmitted?</h4><p><strong>REST Transmission (Human-Readable)</strong></p><p>When you inspect the network with tcpdump or Wireshark, you see:</p><p>→ Client to Server:</p><pre>GET /api/v1/users/user123/profile HTTP/1.1<br>Host: api.myapp.com<br>Accept: application/json<br>Authorization: Bearer &lt;token&gt;</pre><p>← Server to Client:</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br>Content-Length: 156<br>{&quot;id&quot;:&quot;user123&quot;,&quot;name&quot;:&quot;John Doe&quot;,&quot;email&quot;:&quot;john.doe@example.com&quot;,&quot;profilePicture&quot;:&quot;https://cdn.myapp.com/users/123/profile.jpg&quot;}</pre><p>You can <strong>literally read this</strong>. The field names “id”, “name”, “email” are transmitted over the wire as strings.</p><p><strong>gRPC Transmission (Binary-Encoded)</strong></p><p>When you inspect the network, you see:</p><p>→ Client to Server:</p><pre>[HTTP/2 HEADERS]<br>Authorization: Bearer &lt;token&gt;<br>[DATA FRAME - Binary]<br>0a 08 75 73 65 72 31 32 33</pre><p>← Server to Client:</p><pre>[HTTP/2 HEADERS]<br>content-type: application/grpc<br>[DATA FRAMES - Binary]<br>0a 08 75 73 65 72 31 32 33<br>12 08 4a 6f 68 6e 20 44 6f 65<br>1a 15 6a 6f 68 6e 2e 64 6f 65 40 65 78 61 6d 70 6c 65 2e 63 6f 6d<br>22 2a 68 74 74 70 73 3a 2f 2f 63 64 6e 2e 6d 79 61 70 70 2e 63 6f 6d 2f 75 73 65 72 73 2f 31 32 33 2f 70 72 6f 66 69 6c 65 2e 6a 70 67</pre><p>You <strong>cannot read this</strong>. It’s optimized binary. The protobuf compiler uses field numbers (1, 2, 3, 4) instead of names, making it much smaller.</p><h4>Key Differences You Need to Know</h4><p><strong>1</strong>. <strong>Field Names vs Numbers</strong></p><p><strong>REST:</strong> Sends “<em>profilePicture”:</em>“<em>https://...” </em>(20 chars for field name)<br><strong>gRPC:</strong> Sends field tag <em>22</em> (1 byte) + value</p><p>This is why gRPC is smaller — especially with long field names!</p><p><strong>2</strong>. <strong>Schema Evolution</strong></p><p><strong>REST:</strong> Adding a new field changes nothing. Your old client might break if backend assumes it exists.</p><p><strong>gRPC:</strong></p><pre>message GetUserProfileResponse {<br> string id = 1;<br> string name = 2;<br> string email = 3;<br> string profile_picture = 4;<br> string phone_number = 5; // NEW field<br>}</pre><p>Old clients <strong>ignore unknown fields</strong>. This is built into protobuf. Both old and new clients work with the same endpoint!</p><p><strong>3. Error Handling</strong></p><p><strong>REST:</strong> Uses HTTP status codes (200, 400, 404, 500)<br><strong>gRPC:</strong> Uses HTTP/2 trailers with <em>grpc-status</em> code:</p><pre>grpc-status: 5<br>grpc-message: &quot;User not found&quot;</pre><p><strong>4. Streaming Support</strong></p><p><strong>REST:</strong> Need WebSockets for real-time data<br><strong>gRPC:</strong> Native streaming support</p><pre>// Server can stream multiple responses<br>rpc GetUserUpdates(GetUserUpdatesRequest) returns (stream UserUpdate);</pre><h3>When Should You Use Which?</h3><h4>Use REST When:</h4><ul><li>Building public APIs consumed by web browsers</li><li>Need human-readable debugging</li><li>Working with JavaScript-heavy applications</li><li>Building simple CRUD APIs</li><li>Team is new to gRPC</li></ul><h4><strong>Use gRPC When:</strong></h4><ul><li>Building microservices that talk to each other</li><li>Need high performance and low latency</li><li>Building mobile apps where bandwidth matters</li><li>Need bidirectional streaming</li><li>Want strong API contracts</li></ul><h3>The Hidden Details Developers Should Know</h3><h4>Connection Overhead</h4><p><strong>REST (HTTP/1.1):<br></strong>- Opens new TCP connection per request (unless using connection pooling)<br>- Each request = handshake overhead</p><p><strong>gRPC (HTTP/2):<br></strong>- Multiplexes multiple requests over <strong>one</strong> TCP connection<br>- Single handshake, many requests</p><h4><strong>Serialization Performance</strong></h4><p><strong>JSON Deserialization:</strong></p><pre>// Slow - reflection-based parsing<br>Gson().fromJson(jsonString, UserProfile::class.java)</pre><p><strong>Protocol Buffer Deserialization:</strong></p><pre>// Fast - generated code<br>UserProfile.parseFrom(byteArray)</pre><p>Protocol Buffers are <strong>3–10x faster</strong> at parsing. For high-throughput systems, this matters.</p><h4>Wire Protocol Encoding</h4><p><strong>REST (JSON):</strong></p><pre>&quot;profilePicture&quot;: &quot;https://cdn.myapp.com/users/123/profile.jpg&quot;</pre><p>53 bytes total (field name + value)</p><p><strong>gRPC (Protobuf):</strong></p><pre>22 29 68 74 74 70 73 3a 2f 2f 63 64 6e 2e 6d 79 61 70 70 2e 63 6f 6d 2f 75 73 65 72 73 2f 31 32 33 2f 70 72 6f 66 69 6c 65 2e 6a 70 67</pre><p>38 bytes total (field tag + value, no names)</p><h3>Real-World Impact</h3><p>Let me share numbers from payment systems I’ve worked on in production:</p><h4><strong>Scenario 1: Payment Transaction — Instant Money Transfer</strong></h4><p>I worked on a UPI/money transfer feature where users initiate payments frequently. Every millisecond and byte counts.</p><p><strong>REST Implementation:</strong></p><p>- Payment request payload: ~2,500 bytes (lots of metadata in JSON)<br>- Field names like “payment_merchant_id”, “transaction_reference_number”, “beneficiary_account_details” take space<br>- Average API call: 8 KB total (headers + payload)<br>- Latency: 120–180ms (includes JSON serialization overhead)</p><p>- <strong>Problem</strong>: User makes 10 payments/day × 365 days = 3,650 API calls<br>- <strong>Monthly bandwidth:</strong> ~30 MB just for payment requests</p><p><strong>gRPC Implementation:</strong></p><p>- Same data in protobuf: ~1,200 bytes (field numbers instead of names)<br>- Binary encoding is compact: <em>payment_merchant_id</em> becomes field tag <em>3<br></em>- Average API call: 3.5 KB total<br>- Latency: 80–110ms (protobuf deserialization is faster)</p><p>- <strong>Savings</strong>: Same 3,650 API calls but only ~12 MB bandwidth<br>-<strong>Impact</strong>: 60% bandwidth reduction, 25% faster payments</p><h4>Scenario 2: Search Results — Product/Service Discovery</h4><p>Search is called <strong>constantly</strong> — every keystroke, filter change, sorting, pagination.</p><p><strong>REST Implementation:</strong></p><pre>{<br>&quot;query&quot;: &quot;headphones&quot;,<br>&quot;results&quot;: [<br>{<br>&quot;product_id&quot;: &quot;123456&quot;,<br>&quot;product_name&quot;: &quot;Wireless Headphones&quot;,<br>&quot;product_description&quot;: &quot;High quality…&quot;,<br>&quot;price_details&quot;: {…},<br>&quot;merchant_info&quot;: {…},<br>&quot;reviews&quot;: […],<br>&quot;images&quot;: […]<br>}<br>// … 20 more products<br>],<br>&quot;total_count&quot;: 150,<br>&quot;pagination&quot;: {…}<br>}</pre><p>- Response size: 45–80 KB (JSON with verbose field names)<br>- Search queries with 20 results: ~65 KB average<br>- User searches 50 times/day × 30 days = 1,500 searches</p><p>- <strong>Monthly data</strong>: ~95 MB just for search</p><p><strong>gRPC Implementation:</strong></p><p>- Same data compacted: Field <em>product_name</em> → <em>2</em> (tag), <em>product_id</em> → <em>1<br></em>- Response size: 20–35 KB (protobuf binary)<br>- Same 1,500 searches: ~52 MB total</p><p>- <strong>Savings</strong>: 45% less bandwidth</p><blockquote><strong>Combined Impact on User’s Data Plan:</strong></blockquote><blockquote>For a typical active user with both features:</blockquote><blockquote>- <strong>REST total</strong>: ~125 MB/month (payments + search + other APIs)<br>- <strong>gRPC total</strong>: ~64 MB/month<br>- <strong>Savings</strong>: 49% less mobile data usage<br>- U<strong>ser</strong> <strong>feedback</strong>: “The app feels faster and uses less data. My monthly bill went down $8.”</blockquote><h3>Conclusion</h3><p>Both REST and gRPC solve the same problem — getting data from server to client. But they approach it differently:</p><p>- <strong>REST</strong> is like sending a postcard: you can read it, it’s simple, but verbose</p><p>- <strong>gRPC</strong> is like sending a coded telegram: you need a key to read it, but it’s very efficient</p><p>As developers, understanding both helps you choose the right tool. For most web and mobile apps, <strong>start with REST — </strong>it’s simpler and sufficient. But when you need performance, streaming, or have bandwidth constraints, <strong>gRPC is your friend</strong>.</p><p>The key is knowing <strong>what’s actually happening on the wire</strong>. Now that you’ve seen the binary, you understand why gRPC can be smaller and faster, and why REST is easier to debug.</p><p><em>*P.S. Want to see the actual network traffic? Run `tcpdump` or use Wireshark and compare the two — you’ll see exactly what I described above!*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a7e8cf76315" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Flutter + Android Integration Guide]]></title>
            <link>https://medium.com/@sneha_71656/flutter-android-integration-guide-743f9a56ec23?source=rss-84e4a9435d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/743f9a56ec23</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[hybrid-app-development]]></category>
            <dc:creator><![CDATA[Sneha]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 14:29:44 GMT</pubDate>
            <atom:updated>2025-07-06T14:29:44.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1X4PAGaNcuY36GzpXTqt9g.png" /></figure><p>Add Flutter UI to your existing Android app — without rewriting everything.</p><h4>Why Embed Flutter?</h4><p>Sometimes you need a faster dev cycles for experiments or shared code across Android &amp; iOS.<br>But rewriting your whole app in Flutter? <strong>Not ideal.<br></strong>👉 Instead, embed <strong>just one Flutter screen</strong> inside your Android app.</p><h4>🧱 <strong>Architecture Overview</strong></h4><p>Here’s how everything connects:</p><blockquote>Flutter UI (Dart)<br> ↕ MethodChannel<br>Flutter Activity (Kotlin)<br> ↕ ViewModel<br>Repository / API (Kotlin)<br> ↕ Backend</blockquote><p>Think of Flutter as a <strong>custom View</strong> that renders UI using Dart code — but runs <em>inside</em> your Android Activity.</p><h4>🔧 <strong>Project Setup</strong></h4><p><strong>1. Add Dependencies</strong></p><p>In your build.gradle.kts:</p><pre>dependencies {<br>    // Flutter<br>    implementation(&quot;io.flutter:flutter_embedding_release:1.0.0&quot;)<br><br>    // AndroidX<br>    implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0&quot;)<br>    implementation(&quot;androidx.activity:activity-ktx:1.8.2&quot;)<br><br>    // JSON<br>    implementation(&quot;com.google.code.gson:gson:2.10.1&quot;)<br>}</pre><p><strong>2. Setup the Flutter Engine</strong></p><pre>val engine = FlutterEngine(context).apply {<br>    navigationChannel.setInitialRoute(&quot;/&quot;) // like setting the homepage<br>    dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())<br>}<br>FlutterEngineCache.getInstance().put(&quot;main_engine&quot;, engine)</pre><p>We are caching the flutter engine so that the engine is created once and <strong>reused across Flutter screens</strong>, improving performance significantly.</p><h3>📱 Minimal Flutter Activity</h3><h3>🤔 Wait — What is a Flutter Activity?</h3><p>As an Android developer, you’re already familiar with Activity, Fragment, and View.<br>Well, here’s the key:<br> <strong>Flutter is just a really smart View.</strong> It draws its own UI using Dart code — but you embed it inside your Android app like any other View.</p><p>When you write:</p><pre>class CustomFlutterActivity : FlutterFragmentActivity()</pre><p>You’re doing the exact same thing as:</p><pre>class MyActivity : AppCompatActivity()</pre><p>The only difference?<br> Instead of hosting native XML + Views, FlutterFragmentActivity knows how to host <strong>Flutter-rendered UI</strong> from a Dart entrypoint.</p><p>🧠 <strong>Key concept</strong>: Flutter doesn’t take over your app.<br> It simply <strong>runs inside</strong> it — just like adding a WebView or a Fragment.</p><p><strong>Your First Flutter Activity</strong></p><pre>class SimpleFlutterActivity : FlutterFragmentActivity() {<br><br>    private val viewModel: SimpleFlutterViewModel by viewModels()<br><br>    override fun provideFlutterEngine(ctx: Context) =<br>        FlutterEngineCache.getInstance()[&quot;main_engine&quot;]<br><br>    override fun configureFlutterEngine(engine: FlutterEngine) {<br>        setupMethodChannel(engine)<br>    }<br><br>    private fun setupMethodChannel(engine: FlutterEngine) {<br>        MethodChannel(engine.dartExecutor.binaryMessenger, &quot;android_flutter_channel&quot;)<br>            .setMethodCallHandler { call, result -&gt;<br>                when (call.method) {<br>                    &quot;getUserData&quot; -&gt; viewModel.getUserData()<br>                        .whenComplete { data, err -&gt;<br>                            if (err != null) result.error(&quot;USER_ERR&quot;, err.message, null)<br>                            else             result.success(data)<br>                        }<br><br>                    &quot;saveUserData&quot; -&gt; {<br>                        val name  = call.argument&lt;String&gt;(&quot;name&quot;) ?: &quot;&quot;<br>                        val email = call.argument&lt;String&gt;(&quot;email&quot;) ?: &quot;&quot;<br>                        viewModel.saveUserData(name, email)<br>                        result.success(true)<br>                    }<br><br>                    else -&gt; result.notImplemented()<br>                }<br>            }<br>    }<br>}</pre><p>This Activity connects Flutter and Android using a MethodChannel.</p><p>Here’s the ViewModel with all business logic to keep your Activity clean and testable.</p><pre>class SimpleFlutterViewModel : ViewModel() {<br><br>    fun getUserData(): CompletableFuture&lt;String&gt; =<br>        CompletableFuture&lt;String&gt;().also { future -&gt;<br>            viewModelScope.launch(Dispatchers.IO) {<br>                try {<br>                    val data = mapOf(<br>                        &quot;name&quot; to &quot;John Doe&quot;,<br>                        &quot;email&quot; to &quot;john@example.com&quot;,<br>                        &quot;id&quot; to &quot;12345&quot;<br>                    )<br>                    future.complete(Gson().toJson(data))<br>                } catch (e: Exception) {<br>                    future.completeExceptionally(e)<br>                }<br>            }<br>        }<br><br>    fun saveUserData(name: String, email: String) {<br>        viewModelScope.launch(Dispatchers.IO) {<br>            println(&quot;Saving $name &lt;$email&gt;&quot;)<br>        }<br>    }<br>}</pre><p>You’ll notice this method in the ViewModel:</p><pre>fun getUserData(): CompletableFuture&lt;String&gt; { ... }</pre><p>This lets us <strong>safely perform asynchronous work (like API calls or DB access)</strong> in a coroutine, but still <strong>respond to Flutter via a callback</strong>.</p><p>Why not just use suspend functions?<br>Because Flutter talks to Android using <strong>callback-based APIs</strong>, not suspending ones.</p><p>So CompletableFuture acts as a <strong>bridge</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*C3VvM5NAOlXGUYqmQAx3sg.png" /></figure><p>So while your Kotlin code remains idiomatic and coroutine-friendly, you’re also able to play nicely with Flutter’s MethodChannel expectations.</p><h3>📞 Method Channels = Your Flutter ↔ Android Hotline</h3><p>Method Channels are how <strong>Flutter and Android talk to each other</strong>.</p><blockquote><em>Think of it like making a phone call:<br></em><strong>• </strong>You <strong>dial a channel name</strong> (like a phone number)<br><strong>• </strong>You <strong>say a method name</strong> (what you want)<br><strong>• </strong>You <strong>send arguments</strong> (your message)<br><strong>• </strong>You <strong>wait for a response</strong> (or get hung up on 😬)</blockquote><p><strong>☎️ Components of the Call</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpTRiog_qrKNFKN0vgJo5A.png" /></figure><p><strong>📲 Flutter → Android (Calls Kotlin side)</strong></p><pre>final platform = MethodChannel(&#39;android_flutter_channel&#39;);<br><br>// Flutter calls Android and waits for a result<br>final userJson = await platform.invokeMethod(&#39;getUserData&#39;);</pre><pre>// Android listens to the call<br>MethodChannel(engine.dartExecutor.binaryMessenger, &quot;android_flutter_channel&quot;)<br>    .setMethodCallHandler { call, result -&gt;<br>        when (call.method) {<br>            &quot;getUserData&quot; -&gt; {<br>                val user = getUserFromSomewhere()<br>                result.success(Gson().toJson(user))<br>            }<br>            else -&gt; result.notImplemented()<br>        }<br>    }</pre><p><strong>📞 Android → Flutter (Calls Dart side)</strong></p><pre>MethodChannel(engine.dartExecutor.binaryMessenger, &quot;android_flutter_channel&quot;)<br>    .invokeMethod(&quot;updateData&quot;, Gson().toJson(updatedData))</pre><pre>// Flutter listens to Android&#39;s &quot;call&quot;<br>platform.setMethodCallHandler((call) async {<br>  if (call.method == &#39;updateData&#39;) {<br>    final data = jsonDecode(call.arguments);<br>    updateUI(data);<br>  }<br>});</pre><p>🎯 <strong>Tip</strong>: Treat your MethodChannel like a well-documented API.<br> Version it. Validate arguments. Handle unknown methods cleanly.</p><h3>🔄 End-to-End Flow: Get User Profile</h3><ol><li>Flutter calls: &quot;getUserData&quot;</li><li>Android Activity → ViewModel</li><li>ViewModel fetches data → returns JSON</li><li>Activity sends JSON back to Flutter</li><li>Flutter updates UI</li></ol><pre>MethodChannel(engine.dartExecutor.binaryMessenger, &quot;android_flutter_channel&quot;)<br>    .setMethodCallHandler { call, result -&gt;<br>        if (call.method == &quot;getUserData&quot;) {<br>            viewModel.getUserData().whenComplete { data, error -&gt;<br>                if (error != null) result.error(&quot;USER_DATA_ERROR&quot;, error.message, null)<br>                else result.success(data)<br>            }<br>        }<br>    }</pre><h3>🧪 Add Your Own Flutter Module</h3><p>1. Create a module:</p><pre>flutter create --template=module my_flutter_module</pre><p>2. Build AAR:</p><pre>flutter build aar</pre><p>3. Add to Android project:</p><pre>dependencies {<br>    implementation(&quot;com.example.my_flutter_module:flutter_release:1.0&quot;)<br>}</pre><p>4. Launch Flutter screen via your FlutterFragmentActivity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=743f9a56ec23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[As I dived into the world of Jetpack Compose, I discovered not only it’s powerful capabilities but…]]></title>
            <link>https://medium.com/@sneha_71656/as-i-dived-into-the-world-of-jetpack-compose-i-discovered-not-only-its-powerful-capabilities-but-dad138277393?source=rss-84e4a9435d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/dad138277393</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Sneha]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 13:22:20 GMT</pubDate>
            <atom:updated>2023-09-11T14:40:14.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upKeAie3UGAy75vdKdxHbA.png" /><figcaption>𝐉𝐄𝐓𝐏𝐀𝐂𝐊 𝐂𝐎𝐌𝐏𝐎𝐒𝐄 𝐁𝐞𝐬𝐭 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐞𝐬</figcaption></figure><p>As I dived into the world of Jetpack Compose, I discovered not only it’s powerful capabilities but also the subtleties that can make or break an app’s user interface. In this guide, I’d like to share the do’s and don’ts I’ve learned while working with it. These insights will help you keep in mind recomposition, states, layouts, and lifecycle management to create amazing Android apps.</p><h3>• State Management</h3><h3>The Do’s: Making the Most of Recomposition</h3><blockquote>At the heart of Jetpack Compose lies recomposition, a mechanism that drives your UI updates efficiently. Whenever there’s a change in your app’s state, whether through user interactions or data updates, Compose detects it and intelligently redraws only the affected parts of your UI. Recomposition is the secret sauce that keeps your UI reactive and responsive.</blockquote><h4>1. Embrace Immutable State</h4><p>Prioritise the use of immutable data structures for your app’s state. Immutable data structures, like Kotlin’s val, are your allies. They simplify state management and enable Compose to detect changes efficiently.</p><pre>//Recommended<br>val title = &quot;Jetpack compose&quot;<br><br>//Avoid<br>var title = &quot;Jetpack compose&quot;</pre><h4>2. Leverage State Management</h4><p>Use Compose’s built-in state management tools like remember and mutableStateOf. These tools help you manage and propagate changes in your app’s state, triggering recomposition as necessary.</p><pre>// Recommended<br>var count by remember { mutableStateOf(0) } <br><br>// Avoid <br>var count = 0</pre><h4>3. Optimise for performance</h4><p>Performance is paramount. Use remember functions to cache expensive calculations or operations, sparing your app from redundant computation during recomposition.</p><pre>// Recommended<br>val result by remember { calculateExpensiveResult() }<br><br>// Avoid<br>val result = calculateExpensiveResult()</pre><h3>The Don’ts: Avoiding Recomposition Pitfalls</h3><h4>1. Avoid Excessive Mutable State</h4><p>Keep mutable state to a minimum. Excessive mutable variables can lead to unpredictable recomposition.</p><pre>//Don&#39;t do this - Excessive Mutable State<br>@Composable<br>fun ShoppingCart() {<br>    var items: List&lt;CartItem&gt; by remember { mutableStateOf(emptyList()) }<br>    <br>    // Rest of the composable logic...<br><br>    // Imagine a function to add an item to the shopping cart:<br>    fun addItem(item: CartItem) {<br>        items = items.toMutableList().apply { add(item) } // Modifying mutable state<br>    }<br><br>    // Imagine a function to remove an item from the shopping cart:<br>    fun removeItem(item: CartItem) {<br>        items = items.toMutableList().apply { remove(item) } // Modifying mutable state<br>    }<br>}</pre><p>Instead of having all shopping cart-related mutable state within a single composable, it’s better to separate concerns and manage state more granularly. For example, you could use a ViewModel to handle the shopping cart state and expose it to different composables as needed.</p><h4>2. Don’t Use Global Mutable State</h4><p>Overusing global mutable state can make your code harder to understand and maintain.</p><pre>// Don&#39;t do this - Using Global Mutable State<br>object GlobalAppState {<br>    var userLoggedIn = false<br>}<br><br>@Composable<br>fun MyProfileScreen() {<br>    val userLoggedIn = GlobalAppState.userLoggedIn<br>    // Display UI based on userLoggedIn<br><br>    // Imagine later in the code, there&#39;s a button to log the user in:<br>    Button(<br>        onClick = {<br>            GlobalAppState.userLoggedIn = true // Updating global mutable state<br>        }<br>    ) {<br>        Text(&quot;Log In&quot;)<br>    }<br>}</pre><h4>3. Don’t Mix Mutable and Immutable State Unnecessarily</h4><p>While mutable state is essential for some scenarios, avoid mixing it with immutable state unnecessarily. Inconsistent use of state types can lead to confusion and bugs.</p><pre>// Don&#39;t do this<br>var mutableCount by remember { mutableStateOf(0) }<br>val immutableCount = 42</pre><p>Instead, Choose the appropriate type of state (mutable or immutable) based on your needs, but avoid mixing them within the same scope to maintain clarity.</p><h4>4. Don’t Bypass Compose’s State Management</h4><p>Resist the urge to directly update mutable variables without utilising Compose’s state management. This can lead to unpredictable recomposition.</p><h3>• Composable Components and Layouts</h3><h3>The Do’s</h3><h4>1. Leverage Composables</h4><p>Embrace the principle of composition over inheritance in Jetpack Compose. Instead of relying heavily on inheritance for building UI components, create reusable composables. Composition allows you to assemble complex UIs by combining smaller, specialized composables, resulting in more flexible and maintainable code.</p><pre>// Recommended<br>@Composable<br>fun MyButton() {<br>    // ...<br>}<br><br>// Avoid<br>class MyButton : Button() {<br>    // ...<br>}</pre><h4>2. Understand Recomposition Triggers</h4><p>Be aware of what triggers recomposition. Changes to state variables within a composable function or recomposing parent will prompt UI updates.</p><h4>3. Choose LazyColumn and LazyRow for Large Datasets</h4><p>Consider using LazyColumn or LazyRow for vertical and horizontal long lists respectively. They are designed for efficient handling of large datasets. It’s a good alternative for the traditional Recyclerview.</p><pre>// Recommended for long lists<br>LazyColumn {<br>    items(itemsList) { item -&gt;<br>        ListItem(item)<br>    }<br>}</pre><h4>4. Utilise ConstraintLayout for Complex UIs</h4><p>For complex and responsive UI designs, consider using ConstraintLayout. It allows you to define relationships between UI elements, enabling precise control over their placement and behaviour.</p><p>Add this dependency in your build.gradle</p><pre>implementation &quot;androidx.constraintlayout:constraintlayout-compose:1.0.1&quot;</pre><p>Then use it like this:</p><pre>import androidx.compose.foundation.layout.ConstraintLayout<br><br>@Composable<br>fun ConstraintLayoutContent() {<br>    ConstraintLayout {<br>        // Create references for the composables to constrain<br>        val (button, text) = createRefs()<br><br>        Button(<br>            onClick = { /* Do something */ },<br>            // Assign reference &quot;button&quot; to the Button composable<br>            // and constrain it to the top of the ConstraintLayout<br>            modifier = Modifier.constrainAs(button) {<br>                top.linkTo(parent.top, margin = 16.dp)<br>            }<br>        ) {<br>            Text(&quot;Button&quot;)<br>        }<br><br>        // Assign reference &quot;text&quot; to the Text composable<br>        // and constrain it to the bottom of the Button composable<br>        Text(<br>            &quot;Text&quot;,<br>            Modifier.constrainAs(text) {<br>                top.linkTo(button.bottom, margin = 16.dp)<br>            }<br>        )<br>    }<br>}</pre><h3>The Don’ts</h3><h4>1. Don’t Over-Compose</h4><p>While composition is a strength, avoid excessive nesting of composables. It can lead to performance issues and complexity.</p><h4>2. Don’t Use LazyColumn or LazyRow for Static Content</h4><p>Don’t use LazyColumn or LazyRow for static content or small lists where all items fit comfortably on the screen. Using them unnecessarily can introduce unnecessary complexity. Instead use Column or Row. They are simpler and more suitable for such scenarios.</p><pre>@Composable<br>fun MyComposable() {<br>    Column {<br>        items(staticItemList) { item -&gt;<br>            ListItem(item)<br>        }<br>    }<br>}</pre><h4>3. Don’t Add Hardcoded Dimensions</h4><p>It’s crucial to avoid hardcoding dimensions like width and height values for UI elements. Hardcoded dimensions can lead to inflexible layouts that don’t adapt well to different screen sizes and orientations. Instead, Compose offers a powerful system of modifiers and layouts that allow you to create responsive UIs that adjust dynamically based on the device’s characteristics. By embracing these dynamic layout techniques and utilising modifiers like Modifier.fillMaxWidth() and Modifier.fillMaxHeight(), you ensure that your app&#39;s user interface remains adaptable and looks great on a variety of Android devices. This practice promotes a more consistent and user-friendly experience across different screen sizes and orientations.</p><h3>• Lifecycle Management</h3><h3>The Do’s</h3><h4>1. Understand the Lifecycle</h4><p>Familiarize yourself with the Android lifecycle and how it interacts with Jetpack Compose. Understanding the lifecycle is crucial for managing UI updates and avoiding potential issues.</p><h4>2. Use LaunchedEffect for Side Effects</h4><p>When dealing with side effects like fetching data or performing asynchronous operations, use LaunchedEffect. It ensures that these side effects are executed only when the composable is active.</p><h4>3. Embrace Jetpack Navigation</h4><p>Use Jetpack Navigation for defining and managing your app’s navigation flow. It simplifies navigation between different screens and components.</p><h3>The Don’ts</h3><h4>1. Don’t Use Composables for Lifecycle Observing</h4><p>Composables are not meant for observing the Android lifecycle. Avoid directly placing lifecycle observers inside composables.</p><pre>// Don&#39;t do this<br>@Composable<br>fun MyComposable() {<br>    val lifecycleOwner = LocalLifecycleOwner.current<br>    val lifecycle = lifecycleOwner.lifecycle<br><br>    lifecycle.addObserver(MyObserver())<br>}</pre><h4>2. Don’t Perform Heavy Computations in Composables</h4><p>Refrain from performing heavy computations directly within composables, especially when they are triggered by lifecycle events. Heavy computations can impact the app’s responsiveness and user experience.</p><pre>// Don&#39;t do this<br>@Composable<br>fun MyComposable() {<br>    val result = computeExpensiveResult() // Heavy computation!<br>    // ...<br>}</pre><p>Instead, move heavy computations to a background thread and use remember or LaunchedEffect to update the UI when the computation is complete.</p><pre>@Composable<br>fun MyComposable() {<br>    val result by remember { mutableStateOf(&quot;Calculating...&quot;) }<br><br>    LaunchedEffect(Unit) {<br>        withContext(Dispatchers.Default) {<br>            val computationResult = computeExpensiveResult()<br>            result = computationResult // Update the UI with the result<br>        }<br>    }<br><br>    // Display result in the UI<br>}</pre><h4>3. Don’t Use Mutable Variables for UI Configuration</h4><p>Refrain from using mutable variables for configuring UI components. It can lead to unexpected behavior and challenges in managing UI state.</p><pre>// Don&#39;t do this<br>@Composable<br>fun MyComposable() {<br>    var isEnabled = true // Mutable UI configuration!<br>    Button(<br>        onClick = { /* Handle click */ },<br>        enabled = isEnabled<br>    ) {<br>        Text(&quot;Click Me&quot;)<br>    }<br>}</pre><p>Instead, use Composable functions and Compose state to control UI configuration. Compose state ensures that UI updates happen correctly.</p><pre>@Composable<br>fun MyComposable() {<br>    var isEnabled by remember { mutableStateOf(true) }<br><br>    Button(<br>        onClick = { /* Handle click */ },<br>        enabled = isEnabled<br>    ) {<br>        Text(&quot;Click Me&quot;)<br>    }<br>}</pre><h4>4. Don’t Modify State Outside the Composition</h4><p>Avoid modifying Compose state outside the Composable functions. This can disrupt Compose’s reactivity and lead to bugs that are challenging to debug.</p><pre>// Don&#39;t do this<br>var count by remember { mutableStateOf(0) }<br><br>// In some other part of the code<br>count = 42 // Modifying state outside the Composable!</pre><p>As you embark on your journey with Jetpack Compose, remember that it’s not just about writing code, it’s about crafting delightful user experiences. Continuously explore the official documentation, stay up-to-date with the latest developments, and engage with the vibrant Compose community to refine your skills further.</p><p>Happy composing, and may your UIs shine brightly in the world of Android development!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dad138277393" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Development with Multi-Modules]]></title>
            <link>https://medium.com/@sneha_71656/android-development-with-multi-modules-a1f5fe13469?source=rss-84e4a9435d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1f5fe13469</guid>
            <category><![CDATA[multi-module-project]]></category>
            <category><![CDATA[sanity]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Sneha]]></dc:creator>
            <pubDate>Sat, 02 Sep 2023 19:33:05 GMT</pubDate>
            <atom:updated>2023-09-02T19:33:05.758Z</atom:updated>
            <content:encoded><![CDATA[<p>In the fast-paced world of Android app development, the key to success is often hidden in the art of simplicity and maintainability. As your app evolves from a fledgling idea into a robust digital companion, the need to organise and manage your code becomes paramount. This is where the concept of multi-module projects in Android comes into play — a powerful strategy to keep your Android app development journey smooth and your codebase cleaner than ever.</p><p><strong>The Marvel of Multi-Module Projects</strong></p><p>Imagine your Android app as a league of superheroes, where each module embodies a different hero, having a specific power or feature. Let’s delve into why this modular approach is a game-changer for Android developers.</p><p><strong>1. Modularity — Divide and Conquer</strong></p><p>Modularity is the superhero cape your codebase needs. By breaking your app into smaller modules, you’re creating a clear separation of concerns. Each module, whether it’s the UI, data handling, networking, or a third-party integration, has a single mission(for example: to stop Thanos). This clean separation makes your codebase easier to understand and maintain.</p><p><strong>2. Reusability — Sharing is Caring</strong></p><p>Modules are like the Avengers of Android development. When designed correctly, they can be reused in other projects, saving you from rewriting the same code repeatedly. For instance, that networking module you meticulously crafted can be your go-to superhero in multiple apps, reducing redundancy and saving development time.</p><p><strong>3. Parallel Development — Assemble Your Team</strong></p><p>In the world of multi-module projects, different teams or developers can work on separate modules simultaneously, much like assembling a team of superheroes to save the universe. This parallel development speeds up the app’s creation and minimises conflicts between developers, keeping your project on track.</p><p><strong>4. Testing — Ensuring Heroic Feats</strong></p><p>With modules as individual heroes, unit testing becomes a breeze. You can test each module independently, making sure that changes in one module don’t bring down the entire app. It’s like having a set of safety nets to catch any potential issues before they become full-blown disasters.</p><p><strong>5. Scalability — Grow Without Limits</strong></p><p>As your app’s popularity soars, you’ll need to add new features or refine existing ones. Multi-module projects provide the agility to do this without causing chaos. You can seamlessly expand your app’s capabilities without disrupting the harmony of your codebase.</p><p><strong>6. Dependency Management — Mastering the Art</strong></p><p>Modules declare their dependencies explicitly, giving you the power to manage libraries and external integrations with finesse. It’s like putting together a well-organied team, where each member knows their role and follows the leader’s guidance.</p><p><strong>The Epic Quest: Setting up a Multi-Module Project</strong></p><p>Now that we’ve seen the superpowers of multi-module projects, let’s embark on an epic quest to set up one of our own.</p><p><strong>1. Create a New Android Project</strong></p><p>Start your adventure by creating a new Android project in Android Studio. You’ll begin with a single module, usually named ‘app,’ which serves as the app’s entry point.</p><p><strong>2. Identify Your Modules</strong></p><p>Like assembling a superhero team, identify the various components or features of your app that can be modularized. Common modules include ‘app,’ ‘data,’ ‘network,’ ‘ui,’ ‘utils,’ and ‘common.’</p><p><strong>3. Create New Modules</strong></p><p>In Android Studio, channel your inner creator by crafting new modules. Right-click on the project folder, select ‘New,’ and choose ‘Module.’ Follow the wizard to create each module, specifying its type (e.g., Android Library) and dependencies as needed.</p><p><strong>4. Define Module Dependencies</strong></p><p>In your app’s build.gradle file, let the modules forge alliances. Declare dependencies between modules using the ‘implementation’ or ‘api’ keywords. For example, if the app module depends on the ‘data’ and ‘network’ modules, add the following lines:</p><pre>dependencies { <br>   implementation project(&#39;:data&#39;) <br>   implementation project(&#39;:network&#39;) <br>   // ... <br>}</pre><p><strong>5. Organize Code</strong></p><p>With great power comes great responsibility. Place relevant code and resources within their respective modules. Ensure each module has a clear purpose and minimal dependencies on others. Keep communication between modules clean by defining well-documented interfaces and contracts.</p><p><strong>6. Gradle Settings — Fortify Your Project</strong></p><p>In your project’s settings.gradle file, assemble the modules into a formidable squad:</p><pre>include &#39;:app&#39;, &#39;:data&#39;, &#39;:network&#39;, &#39;:ui&#39;, &#39;:utils&#39;, &#39;:common&#39;</pre><p><strong>7. Building and Running — Witness the Magic</strong></p><p>You’re now ready to build and run your app. Android Studio will handle the compilation and dependency resolution between modules automatically.</p><p><strong>Conclusion</strong></p><p>Multi-module projects in Android are your secret weapons for creating clean, maintainable, and scalable apps. By following this guide, you’ve learned how to set up a multi-module project and harness the superhero-like powers it brings to your Android app development journey.<strong> <br><em>So go forth, build amazing apps, and remember — with great modularity comes great codebase sanity!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1f5fe13469" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>