<?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 Bahar on Medium]]></title>
        <description><![CDATA[Stories by Bahar on Medium]]></description>
        <link>https://medium.com/@mahbooberezaee68?source=rss-33aceb473967------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m2aHUi9cX7pUA8Rxq_EO8w.jpeg</url>
            <title>Stories by Bahar on Medium</title>
            <link>https://medium.com/@mahbooberezaee68?source=rss-33aceb473967------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:46:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahbooberezaee68/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[Jetpack Compose and Nine-Patch Drawables: Common Issues and Solutions]]></title>
            <link>https://medium.com/@mahbooberezaee68/jetpack-compose-and-nine-patch-drawables-common-issues-and-solutions-ddb84b9e44e0?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddb84b9e44e0</guid>
            <category><![CDATA[image]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-views]]></category>
            <category><![CDATA[nine-patch-generator]]></category>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 11:43:34 GMT</pubDate>
            <atom:updated>2026-11-21T12:31:31.659Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever exported an image from Figma and found yourself needing to use <a href="https://romannurik.github.io/AndroidAssetStudio/nine-patches.html">Nine-Patch</a> (.9.png) to make it work properly across different screen sizes?</p><p>When working with PNG illustrations and assets in Android, how do you usually handle different screen densities and device sizes? Do you convert your PNGs to WebP, export multiple density-specific versions (mdpi, hdpi, xhdpi, etc.), use vector drawables, or rely on another approach? I’d love to hear how you handle image assets in your Android projects and what workflow works best for you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0V9A8cC8ocrK0hSZ1DHHxg.png" /><figcaption>Simple nine-patch generator</figcaption></figure><p>Nine-Patch (.9.png) is a special Android drawable format that allows images to stretch dynamically while preserving the appearance of their corners and borders.</p><p>However, loading Nine-Patch drawables (.9.png) as standard image resources in Jetpack Compose is not natively supported and can lead to runtime crashes. Unlike standard bitmap and vector drawables, Nine-Patch resources require special handling to preserve their stretching behavior.</p><p>You may have encountered a runtime crash during composition with an error similar to this:</p><pre>androidx.compose.ui.res.ResourceResolutionException: Error attempting to load resource: res/drawable-xxhdpi-v4/img_empty_promotion.9.png<br>at androidx.compose.ui.res.PainterResources_androidKt.loadImageBitmapResource(PainterResources.android.kt:112)<br>at androidx.compose.ui.res.PainterResources_androidKt.painterResource(PainterResources.android.kt:72)</pre><p>At first glance, this might seem like a missing resource or a corrupted image file. However, the real issue lies in the fundamental differences between how Android’s View system handles drawable resources and how Jetpack Compose loads and renders them.</p><h3>Why Nine-Patch Drawables Work Differently in Jetpack Compose</h3><p>In traditional Android XML-based layouts, Nine-Patch drawables (.9.png) are widely used to create scalable UI elements. They allow bitmaps to stretch dynamically while preserving the appearance of their corners and borders, making them ideal for chat bubbles, backgrounds, and buttons.</p><p>When a <strong><em>.9.png</em></strong> resource is used in an <strong><em>ImageView</em></strong> or as a background in the traditional View system, Android handles it natively through <strong><em>NinePatchDrawable</em></strong>. The framework interprets the one-pixel border markers to identify stretchable regions and content padding, ensuring that the image scales correctly without distorting its important details.</p><p>However, Jetpack Compose takes a different approach to image rendering.</p><p>Here’s where things get interesting:</p><ol><li><strong>painterResource(id)</strong> is designed to load standard bitmap and vector resources into Compose&#39;s <strong><em>Painter</em></strong> system.</li><li><strong>Nine-Patch metadata:</strong> When Android processes a <strong><em>.9.png</em></strong> resource, it associates the bitmap with Nine-Patch metadata (ninePatchChunk), which contains the information needed for proper scaling.</li><li><strong>The compatibility issue:</strong> Compose’s <strong><em>painterResource()</em></strong> does not provide native support for rendering <strong><em>NinePatchDrawable </em></strong>resources. As a result, attempting to load a Nine-Patch drawable through this API can throw a runtime exception, such as <strong><em>ResourceResolutionException</em></strong>.</li></ol><p>This difference between the traditional Android View system and Compose’s resource-handling mechanism is the root of the problem.</p><h3>Why Does It Work in XML Layouts?</h3><p>The same <strong><em>.9.png</em></strong> resource works perfectly in traditional Android XML layouts, whether used in an ImageView or as a background.</p><p>This is because Android’s View system natively supports NinePatchDrawable, whereas Jetpack Compose’s painterResource() does not provide equivalent support.</p><h3>How to Fix It</h3><p>Depending on your project’s requirements, there are two main approaches to handling Nine-Patch drawables in Jetpack Compose.</p><h3>Solution 1: Use AndroidView with ImageView</h3><p><em>Recommended when you need to preserve native Nine-Patch stretching behavior.</em></p><p>If your asset relies on Nine-Patch scaling and you don’t want to replace or modify it, you can use AndroidView to embed a traditional Android ImageView inside your Compose UI.</p><pre>import android.widget.ImageView<br>import androidx.compose.foundation.layout.size<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.unit.dp<br>import androidx.compose.ui.viewinterop.AndroidView<br>import com.example.app.R<br><br>@Composable<br>fun EmptyPromotionScreen() {<br>    AndroidView(<br>        modifier = Modifier.size(220.dp),<br>        factory = { context -&gt;<br>            ImageView(context).apply {<br>                setImageResource(R.drawable.img_empty_promotion)<br>                scaleType = ImageView.ScaleType.FIT_CENTER<br>            }<br>        }<br>    )<br>}</pre><p>By delegating image rendering to ImageView, Android can handle the .9.png resource through its native NinePatchDrawable implementation.</p><p>This approach preserves Nine-Patch stretching behavior while allowing you to use the drawable within your Jetpack Compose UI.</p><h3>Solution 2: Use AndroidView with Background</h3><p>If you want to use a Nine-Patch drawable as the background of a Compose component rather than displaying it as an image, you can use AndroidView with a standard Android View.</p><p>By assigning the Nine-Patch resource to the View’s background, Android automatically handles the stretchable regions and content padding through its native NinePatchDrawable implementation.</p><pre>AndroidView(<br>    factory = { context -&gt;<br>        View(context).apply {<br>            background = ContextCompat.getDrawable(<br>                context,<br>                R.drawable.img_empty_new_promotion<br>            )<br>        }<br>    },<br>    modifier = Modifier.size(200.dp)<br>)</pre><p>This is particularly useful for backgrounds that need to resize dynamically while preserving their corners, borders, and internal content areas.</p><h3>Conclusion</h3><p>Jetpack Compose brings a modern, declarative approach to Android UI development. However, working with legacy resource formats like Nine-Patch (.9.png) requires understanding the differences between the traditional Android View system and Compose’s rendering mechanism.</p><p>Here’s a quick summary of the available solutions:</p><p>- <strong>Use AndroidView with ImageView</strong> if you need to keep the .9.png format and preserve its native stretching behavior.<br>- <strong>Use AndroidView with a standard View</strong> if you want to apply a Nine-Patch drawable as a background.<br>- <strong>Convert to a standard PNG or Vector Drawable</strong> if your image doesn’t require dynamic stretching. This is usually the simplest and most Compose-friendly approach.</p><p>Ultimately, choose the solution that best fits your asset’s requirements. If Nine-Patch functionality isn’t essential, prefer standard image resources to keep your Compose UI simple and avoid unnecessary View interoperability.</p><p><strong>Happy coding!</strong></p><p>This article has explored <strong>Jetpack Compose and Nine-Patch Drawables: Common Issues and Solutions</strong>. I hope you’ve found it informative and engaging. If you enjoyed this content, feel free to show your support by clapping 👏, following, or leaving a comment below suggesting future topics you’d like to see covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddb84b9e44e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spotly: Build Stunning, Interactive Onboarding Experiences with Jetpack Compose]]></title>
            <link>https://medium.com/@mahbooberezaee68/building-a-stunning-feature-rich-onboarding-spotlight-library-in-jetpack-compose-spotly-24842902e7d9?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/24842902e7d9</guid>
            <category><![CDATA[spotly-onboarding]]></category>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 13:12:17 GMT</pubDate>
            <atom:updated>2026-10-21T08:06:16.565Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever opened an app for the first time and seen a small highlight around a button or feature, with a short explanation telling you what it does?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*-WKNteMSl13o-Tld-y-VDA.gif" /></figure><p>These small interactions can make a big difference. They help users discover features, understand how an app works, and feel more confident navigating it.</p><p>Inspired by a UI component created by <a href="https://medium.com/@negarmirrasouli">our senior product designer</a> at <a href="https://alopeyk.com/">Alopeyk</a>, I decided to build <strong>Spotly</strong> — a Jetpack Compose library designed to make interactive onboarding and feature discovery more flexible, animated, and customizable.</p><p>Spotly goes beyond traditional onboarding flows. It combines animated spotlights, live UI targeting, image-based guides, and customizable content into a single, Compose-friendly solution.</p><h3>Why Spotly?</h3><p>Traditional onboarding libraries can be restrictive. Some support only simple rectangular highlights, while others make it difficult to combine live UI elements with custom illustrations or create more advanced onboarding flows.</p><p>Spotly was designed to address these limitations using Jetpack Compose’s declarative UI approach.</p><p>Here are some of its key features:</p><ul><li><strong>Morphing Multi-Spotlights:</strong> Highlight multiple UI elements simultaneously with smooth animations and a variety of shapes, including circles, rounded rectangles, ovals, stars, and custom rectangles.</li><li><strong>Hybrid Onboarding Guides:</strong> Combine image-based onboarding illustrations with live UI coordinate tracking through <em>targetRect</em>.</li><li><strong>Card Carousels and Auto-Advance:</strong> Display multiple cards within a feature group, automatically advance between them, and optionally loop through the group.</li><li><strong>Smart Progress Tracking:</strong> Keep progress indicators focused on the main onboarding steps instead of counting every carousel card as a separate step.</li><li><strong>Fully Customizable UI:</strong> Replace the default bottom content with your own designs using SpotlyBottomContentData to match your app&#39;s branding.</li><li><strong>Compose-Friendly Integration:</strong> Integrate the guide manager directly into your Compose UI and control navigation through state and callbacks.</li></ul><h3>Core Features &amp; Architecture</h3><h4>1. Defining Guide Steps (GuideStep)</h4><p>Spotly uses GuideStep to describe each step in an onboarding flow. A step can target a live UI element or display an image-based illustration.</p><p>For example, imagine introducing users to a filter chip that helps them find available work shifts:</p><pre>GuideStep(<br>    title = &quot;Smart Shift Filter&quot;,<br>    description = &quot;Filter your working shifts by day and time effortlessly.&quot;,<br>    targetRect = shiftsFilterChipRect, // Live UI target<br>    spotlights = listOf(<br>        SpotlightShape(<br>            offsetDp = DpOffset(0.dp, 0.dp),<br>            shape = TargetShape.RoundedRect(widthDp = 180.dp, heightDp = 48.dp, cornerRadiusDp = 12.dp)<br>        )<br>    )<br>)</pre><p>In this example:</p><ul><li>title and description explain the feature.</li><li>targetRect identifies the live UI element to highlight.</li><li>spotlights defines the highlight&#39;s shape, dimensions, and offset.</li></ul><p>This approach lets you create contextual onboarding experiences that guide users through the actual interface rather than relying exclusively on static screenshots.</p><h4>2. Create Card Carousels with Automatic Advancement</h4><p>Sometimes, a single feature needs more than one explanation. For example, a shift-booking screen might contain several cards describing capacity, availability, and booking status.</p><p>Spotly supports grouped steps, allowing multiple cards to belong to one feature section.</p><pre>GuideStep(<br>    title = &quot;Shift Status Cards&quot;,<br>    description = &quot;Review shift capacities before booking.&quot;,<br>    imageRes = R.drawable.img_shift_onboarding_step345,<br>    groupId = &quot;shift_carousel_group&quot;,<br>    progressMode = ProgressMode.GROUP_STATIC,<br>    isAutoAdvance = true,<br>    isLooping = true,<br>    autoAdvanceDurationMillis = 2000L<br>)</pre><p>With this configuration, the guide can automatically advance every two seconds and loop through the group when looping is enabled.</p><p>Grouping also helps keep the progress indicator meaningful. Instead of treating every card as a separate top-level onboarding step, Spotly can represent a group as a single feature section.</p><p>This is particularly useful when you want to explain a complex feature without making the overall onboarding journey feel unnecessarily long.</p><h4>3. Integrating SpotlyGuideManager</h4><p>Once your steps are defined, displaying the onboarding experience is straightforward.</p><pre>if (isGuideVisible) {<br>    SpotlyGuideManager(<br>        steps = sampleSteps,<br>        currentStepIndex = currentIndex,<br>        onNextStep = { currentIndex++ },<br>        onPreviousStep = { currentIndex-- },<br>        onSkipOrFinish = { isGuideVisible = false },<br>        colors = SpotlyColors(<br>            overlayColor = Color.Black.copy(alpha = 0.65f),<br>            containerBackground = Color(0xFF3200EE),<br>            titleColor = Color.White<br>        ),<br>        bottomContent = { data -&gt;<br>            CustomSampleBottomContent(data = data)<br>        }<br>    )<br>}</pre><p>This example demonstrates how to:</p><ul><li>Control guide visibility using Compose state.</li><li>Navigate forward and backward between steps.</li><li>Finish or skip the onboarding flow.</li><li>Customize overlay and container colors.</li><li>Provide your own bottom content instead of relying on the default design.</li></ul><p>The bottomSheet parameter is especially useful when you want the onboarding UI to feel like a natural extension of your application rather than a separate component.</p><h3>Why Onboarding Needs Native Analytics &amp; Error Tracking</h3><p>Spotly is designed with production apps in mind. It treats analytics and error monitoring not as an afterthought, but as a core capability:<br>• <em>Step-Level Identification (trackingTag)</em>: Attach a unique tracking tag to any GuideStep (e.g., trackingTag = “shift-onboarding_page-view”).<br>• <em>Action-Driven Funnels (OnboardingAction)</em>: Spotly automatically intercepts user interactions (PAGE_VIEW, NEXT_CLICK, PREVIOUS_CLICK, SKIP_CLICK, FINISH_CLICK).<br>• <em>Fully Dynamic &amp; Unopinionated</em>: Because Spotly provides a clean onTrackingEvent callback, you are never locked into a specific naming convention or SDK. You can map actions to whatever event names your Sentry or Firebase setup requires.</p><h3>How Tracking Works in Practice</h3><p>Here is how simple it is to integrate Spotly’s tracking capabilities with Sentry and Firebase Analytics in your Jetpack Compose app:</p><pre>SpotlyGuideManager(<br>    steps = sampleSteps,<br>    currentStepIndex = currentIndex,<br>    onNextStep = { currentIndex++ },<br>    onPreviousStep = { currentIndex-- },<br>    onSkipOrFinish = { isGuideVisible = false },<br>    onTrackingEvent = { trackingTag, action -&gt;<br>        // 1. Map Spotly&#39;s OnboardingAction to your custom event naming schema<br>        val eventName = when (action) {<br>            OnboardingAction.PAGE_VIEW -&gt; &quot;shift-onboarding_page_view&quot;<br>            OnboardingAction.NEXT_CLICK -&gt; &quot;shift-onboarding_next_click&quot;<br>            OnboardingAction.PREVIOUS_CLICK -&gt; &quot;shift-onboarding_previous_click&quot;<br>            OnboardingAction.SKIP_CLICK -&gt; &quot;shift-onboarding_skip_click&quot;<br>            OnboardingAction.FINISH_CLICK -&gt; &quot;shift-onboarding_finish_click&quot;<br>        }<br><br>        // 2. Attach context to Sentry for error reporting &amp; breadcrumbs<br>        Sentry.addBreadcrumb(&quot;User performed $eventName on step: $trackingTag&quot;)<br>        Sentry.setTag(&quot;onboarding_step_tag&quot;, trackingTag)<br>        Sentry.setTag(&quot;onboarding_action&quot;, eventName)<br><br>        // 3. Log to Firebase Analytics for conversion funnels<br>        firebaseAnalytics.logEvent(eventName, Bundle().apply {<br>            putString(&quot;tracking_tag&quot;, trackingTag)<br>        })<br>    },<br>    colors = SpotlyColors(...),<br>    bottomContent = { data -&gt; CustomSampleBottomContent(data = data) }<br>)</pre><h3>Try the Sample App</h3><p>The library repository includes a fully functional sample application featuring:<br>• A 3-tab Bottom Navigation Bar (Dashboard, Shifts, Profile).<br>• Section-based guide triggers.<br>• Dark Mode toggle and language switching.<br>• A polished edge-to-edge bottom sheet design.</p><h3>Get Started Today!</h3><p>Add Spotly to your project dependencies and elevate your app’s onboarding experience.<br>• GitHub: <a href="https://github.com/Bahar-Developer/spotly-onboarding.git">https://github.com/Bahar-Developer/spotly-onboarding.git</a><br>• MavenCentral:</p><pre>implementation &#39;io.github.bahar-developer:spotly-onboarding:last version&#39;</pre><p>If you find Spotly helpful, please star the repository on GitHub and share your feedback!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24842902e7d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-Tab Navigation Principles in Jetpack Compose: How to Avoid Graph Overlap and Back Stack]]></title>
            <link>https://medium.com/@mahbooberezaee68/cross-tab-navigation-principles-in-jetpack-compose-how-to-avoid-graph-overlap-and-back-stack-a7f3b7217895?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7f3b7217895</guid>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 10:28:33 GMT</pubDate>
            <atom:updated>2026-04-20T10:28:33.567Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern Android development with Jetpack Compose, using a Bottom Navigation with nested graphs is a very common and effective pattern. With the introduction of Type-Safe Navigation in the Navigation Compose library (powered by kotlinx.serialization), implementing this pattern has become significantly safer and more readable.</p><p>However, a recurring challenge for developers (Like me 🫡 in <a href="https://zapexpress.com/">Alopeyk</a> ) using this architecture is implementing direct navigation from a subgraph in one tab to a subgraph in another. In this article, we will explore how to achieve this correctly to prevent the common issue of Back Stack Accumulation and graph conflicts.</p><p><strong>The Challenge of Cross-Tab Navigation</strong></p><p>Imagine an application with a Bottom Navigation containing four tabs (e.g., Home, Search, Cart, Profile). Each tab has its own independent graph (navigation), which in turn contains several composable screens.</p><p>Now, consider a scenario where the user is on a nested screen within the “Home” tab (e.g., a promotion detail screen) and clicks a button that should take them directly to the Profile Settings screen within the Profile tab.</p><p>What happens if we simply use a basic navController.navigate(ProfileSettingsScreen) command?</p><p>The profile screen will open, but it gets pushed onto the “Home” tab’s back stack! This means when the user presses the back button, they are illogically navigated between screens from two different tabs, severely degrading the user experience (UX).</p><p><strong>Type-Safe Navigation + Proper Back Stack Management</strong></p><p>Fortunately, in a Type-Safe approach, all routes are globally defined and accessible. This means we don’t need to navigate back to the root of the app to switch tabs; we can call the destination directly. However, the critical part of the solution is using the popUpTo options within the navigate call to manage the back stack correctly.</p><p><strong>Step-by-Step Implementation</strong></p><p>1. Defining Routes in a Type-Safe Manner:</p><p>First, we define our graphs and screens using the @Serializable annotation. If a screen requires parameters (like ProfileDetailScreen), we define it as a data class:</p><pre>import kotlinx.serialization.Serializable<br><br>// --- Main Graphs (Tabs) ---<br>@Serializable<br>object HomeGraph<br><br>@Serializable<br>object ProfileGraph<br><br>// --- Screens within the Home Tab ---<br>@Serializable<br>object HomeRootScreen<br><br>@Serializable<br>object HomeDetailScreen<br><br>// --- Screens within the Profile Tab ---<br>@Serializable<br>object ProfileRootScreen<br><br>@Serializable<br>data class ProfileDetailScreen(val userId: Int) // A screen that takes an argument</pre><p>2. Structuring the NavHost and Nested Graphs</p><p>Here, we build the graphs for each tab using the navigation builder block:</p><pre>import androidx.compose.runtime.Composable<br>import androidx.navigation.compose.NavHost<br>import androidx.navigation.compose.composable<br>import androidx.navigation.compose.navigation<br>import androidx.navigation.compose.rememberNavController<br><br>@Composable<br>fun MainNavigation() {<br>    val navController = rememberNavController()<br><br>    NavHost(<br>        navController = navController,<br>        startDestination = HomeGraph<br>    ) {<br>        // --- Home Tab Graph ---<br>        navigation&lt;HomeGraph&gt;(startDestination = HomeRootScreen) {<br>            composable&lt;HomeRootScreen&gt; {<br>                // Home root screen composable<br>            }<br>            composable&lt;HomeDetailScreen&gt; {<br>                // Let&#39;s assume this screen has a button to navigate to a profile<br>                HomeDetailScreenUi(<br>                    onNavigateToProfileDetail = { userId -&gt;<br>                        // Calling our navigation function<br>                        navigateToProfileDetail(navController, userId)<br>                    }<br>                )<br>            }<br>        }<br><br>        // --- Profile Tab Graph ---<br>        navigation&lt;ProfileGraph&gt;(startDestination = ProfileRootScreen) {<br>            composable&lt;ProfileRootScreen&gt; {<br>                // Profile root screen composable<br>            }<br>            composable&lt;ProfileDetailScreen&gt; { backStackEntry -&gt;<br>                // Type-safe argument retrieval<br>                val profileArgs = backStackEntry.toRoute&lt;ProfileDetailScreen&gt;()<br>                ProfileDetailScreenUi(userId = profileArgs.userId)<br>            }<br>        }<br>    }<br>}</pre><p>3. Managing Navigation and Preventing Stack Accumulation (The Key Part)</p><p>Now, let’s implement the navigateToProfileDetail function. To prevent the current tab’s stack from accumulating on top of the new one, we must apply navigation options that reference the graph’s start destination:</p><pre>import androidx.navigation.NavController<br>import androidx.navigation.NavGraph.Companion.findStartDestination<br><br>fun navigateToProfileDetail(navController: NavController, userId: Int) {<br>    navController.navigate(ProfileDetailScreen(userId = userId)) {<br>        // 1. Prevents building up a large stack of destinations<br>        // on the back stack as users select items.<br>        popUpTo(navController.graph.findStartDestination().id) {<br>            saveState = true // Save the state of the tab we are leaving<br>        }<br>        <br>        // 2. Avoids multiple copies of the same destination when<br>        // re-selecting the same item<br>        launchSingleTop = true <br>        <br>        // 3. Restores state when re-selecting a previously selected item<br>        restoreState = true <br>    }<br>}</pre><p><strong>Creating a Navigation Helper to Keep Your Code Clean</strong></p><p>If you need to perform this cross-tab navigation from multiple places in your app, repeating the same popUpTo, saveState, and restoreState logic every time violates the DRY (Don’t Repeat Yourself) principle and clutters your UI code.</p><p>Since Type-Safe Navigation in Jetpack Compose uses classes and objects (which are essentially of type Any) to represent routes, the best approach is to create a generic Extension Function for your NavController. So, create a file named <em>NavigationExtensions.kt</em> and add the following helper:</p><pre>import androidx.navigation.NavController<br>import androidx.navigation.NavGraph.Companion.findStartDestination<br><br>/**<br> * A helper extension function for navigating between different bottom navigation tabs<br> * or their nested graphs while preventing back stack accumulation and preserving state.<br> */<br>fun &lt;T : Any&gt; NavController.navigateCrossTab(route: T) {<br>    this.navigate(route) {<br>        // Pop up to the start destination of the graph to<br>        // avoid building up a large stack of destinations<br>        popUpTo(this@navigateCrossTab.graph.findStartDestination().id) {<br>            saveState = true<br>        }<br>        // Avoid multiple copies of the same destination<br>        launchSingleTop = true<br>        // Restore state when reselecting a previously selected item<br>        restoreState = true<br>    }<br>}</pre><p>How to use it in your screens:<br>Now, whenever you want to navigate from a screen in one tab to a screen in another tab, your code becomes incredibly simple and clean. You just pass your type-safe route to the helper:</p><pre>// 1. Navigating to the root of another tab<br>Button(onClick = { navController.navigateCrossTab(ProfileScreen) }) {<br>    Text(&quot;Go to Profile Tab&quot;)<br>}<br><br>// 2. Navigating directly to a deep/nested screen in another tab with arguments<br>Button(onClick = { navController.navigateCrossTab(ProfileDetailScreen(userId = 123)) }) {<br>    Text(&quot;Go directly to User 123&#39;s Profile&quot;)<br>}</pre><p>By using this extension, you centralize your back stack management logic. If you ever need to tweak how your cross-tab navigation behaves, you only have to update it in one single place!</p><p>By combining the direct routing capability of Type-Safe Navigation with the careful use of popUpTo, saveState, and restoreState, we can seamlessly navigate users between nested screens across different tabs. This approach not only keeps our code clean and direct but also perfectly preserves the standard back navigation behavior expected in a Bottom Navigation architecture.</p><p>This article has explored <strong>Cross-Tab Navigation Principles in Jetpack Compose: How to Avoid Graph Overlap and Back Stack</strong>. I hope you’ve found it informative and engaging. If you enjoyed this content, feel free to show your support by clapping 👏, following, or leaving a comment below suggesting future topics you’d like to see covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7f3b7217895" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Android DownloadManager Fails on Restricted Networks (Intranet) and How OkHttp Fixes It During…]]></title>
            <link>https://medium.com/@mahbooberezaee68/why-android-downloadmanager-fails-on-restricted-networks-intranet-and-how-okhttp-fixes-it-during-4d283bec5b91?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d283bec5b91</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 19:43:46 GMT</pubDate>
            <atom:updated>2026-04-18T20:10:36.203Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why Android DownloadManager Fails on Restricted Networks (Intranet) and How OkHttp Fixes It</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*pjxV7s-4GIBZdYHKN1rI8Q.jpeg" /><figcaption>Update and Install App With okHttp in Intranet</figcaption></figure><p>During severe internet restrictions, our engineering team at Alopeyk faced an unexpected challenge. Updating the app for our drivers is always a sensitive process, and after week of being limited to the national intranet, we needed to release an important update. Because our download servers were hosted locally, we confidently started the rollout, thinking the in-app direct download would work fine without international internet. However, support reports quickly showed that the system was broken; drivers clicked the download button, but no file downloaded and the update failed to install. This article explains the technical reasons behind this issue and why Android’s DownloadManager fails on restricted networks.<br><br> <strong>Root Cause Analysis</strong><br>Initially, we suspected a server-side or DNS issue. However, our investigations revealed that the servers were perfectly healthy, and users could easily download the APK file via their mobile web browsers. So, why couldn’t the app fetch the file? The answer lay in the tool we had chosen to manage the downloads: the Android DownloadManager.<br>We had relied on the DownloadManager system service to handle the download queue, display progress notifications, and manage file storage. From a software architecture perspective, this is the standard and most optimal choice—but absolutely not for restricted networks!<br><br><strong>Why Does DownloadManager Fail on a National Intranet?</strong><br>To determine whether a device has actual internet access, the Android operating system relies on a mechanism called Captive Portal Detection. In the background, Android periodically sends an HTTP request to Google servers (such as clients3.google.com/generate_204) to validate the network status.<br><br><strong>During the switch to a national intranet:</strong><br>. The connection to Google servers drops entirely.<br>. The Android OS immediately changes the network status to “Connected, no internet” (displaying the infamous exclamation mark ! next to the Wi-Fi or cellular data icon).<br>. The DownloadManager service, which is deeply tightly coupled to the OS-reported network state, detects this “no internet” flag.<br>. Consequently, the service smartly (but mistakenly in this specific scenario) places the download task in a Pending or Paused state, waiting for “real” internet access to be restored. It never even attempts to ping our internal server!</p><pre>private fun downloadUpdate(url: String): Flow&lt;DownloadStatus&gt; = flow {<br>        val context = ZapApp.appContext.applicationContext<br>        val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager<br>        val request = createDownloadRequest(url)<br>        val downloadId = downloadManager.enqueue(request)<br><br>        var downloading = true<br><br>        while (downloading) {<br>            delay(500)<br><br>            val query = DownloadManager.Query().setFilterById(downloadId)<br>            val cursor = downloadManager.query(query)<br><br>            if (cursor.moveToFirst()) {<br>                val status = getIntSafe(cursor, DownloadManager.COLUMN_STATUS)<br>                val downloaded =<br>                    getIntSafe(cursor, DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR) ?: 0<br>                val total =<br>                    getIntSafe(cursor, DownloadManager.COLUMN_TOTAL_SIZE_BYTES) ?: -1<br><br>                if (total &gt; 0) {<br>                    val progress = ((downloaded * 100L) / total).toInt()<br>                    emit(DownloadStatus.Progress(progress))<br>                }<br><br>                when (status) {<br>                    DownloadManager.STATUS_SUCCESSFUL -&gt; {<br>                        val uriString = getStringSafe(cursor, DownloadManager.COLUMN_LOCAL_URI)<br>                        val file = uriString?.toUri()?.path?.let { File(it) }<br>                        if (file != null &amp;&amp; file.exists()) {<br>                            emit(DownloadStatus.Success(file))<br>                        } else {<br>                            emit(DownloadStatus.Failed(Exception(&quot;File not found&quot;)))<br>                        }<br>                        downloading = false<br>                    }<br><br>                    DownloadManager.STATUS_FAILED -&gt; {<br>                        emit(DownloadStatus.Failed(Exception(&quot;Download failed&quot;)))<br>                        downloading = false<br>                    }<br>                }<br>            }<br>            cursor.close()<br>        }<br>    }</pre><p><strong>The Solution: Bypassing the OS with OkHttp<br></strong>To resolve this critical crisis that was disrupting our fleet operations, we had to completely decouple our download mechanism from Android’s built-in network validation. We decided to deprecate DownloadManager for this flow and rewrite the download logic using OkHttp and Kotlin Coroutines. Unlike Android’s system download service, standard HTTP clients like OkHttp operate completely independently of OS-level network labels. When we fired the download request to our internal server (dl.alopeyk.com/...) using OkHttp, the library bypassed the OS validation and directly opened a socket connection to our IP address. Since the internal network routing was intact, the file streamed down perfectly and was successfully installed on the couriers’ devices.</p><pre>private fun downloadUpdate(url: String): Flow&lt;DownloadStatus&gt; = callbackFlow {<br>    val context = ZapApp.appContext.applicationContext<br>    val dest = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), &quot;app_update.apk&quot;)<br><br>    val job = launch(Dispatchers.IO) {<br>        try {<br>            val client = OkHttpClient.Builder()<br>                .followRedirects(true)<br>                .followSslRedirects(true)<br>                .callTimeout(5, java.util.concurrent.TimeUnit.MINUTES)<br>                .build()<br><br>            val req = Request.Builder()<br>                ./service/https://medium.com/url(url)<br>                .header(&quot;User-Agent&quot;, &quot;Mozilla/5.0 (Linux; Android)&quot;)<br>                .build()<br><br>            client.newCall(req).execute().use { resp -&gt;<br>                if (!resp.isSuccessful) throw Exception(&quot;HTTP ${resp.code}&quot;)<br>                val body = resp.body ?: throw Exception(&quot;Empty body&quot;)<br>                val total = body.contentLength()<br>                dest.parentFile?.mkdirs()<br>                dest.outputStream().buffered().use { fos -&gt;<br>                    val input = body.byteStream()<br>                    val buffer = ByteArray(8 * 1024)<br>                    var read: Int<br>                    var downloaded = 0L<br>                    var lastPct = -1<br>                    while (input.read(buffer).also { read = it } != -1) {<br>                        fos.write(buffer, 0, read)<br>                        downloaded += read<br>                        if (total &gt; 0) {<br>                            val pct = (downloaded * 100 / total).toInt()<br>                            if (pct != lastPct) {<br>                                lastPct = pct<br>                                trySend(DownloadStatus.Progress(pct))<br>                            }<br>                        }<br>                    }<br>                    fos.flush()<br>                }<br>            }<br><br>            if (dest.exists() &amp;&amp; dest.length() &gt; 0) trySend(DownloadStatus.Success(dest))<br>            else trySend(DownloadStatus.Failed(Exception(&quot;Downloaded file is empty&quot;)))<br><br>        } catch (e: Exception) {<br>            trySend(DownloadStatus.Failed(e))<br>        } finally {<br><br>            close()<br>        }<br>    }<br><br>    awaitClose { job.cancel() }<br>}</pre><p><strong>Conclusion<br></strong>This incident served as a massive engineering lesson for our team: when developing applications that must remain operational under unstable or heavily restricted network conditions (such as a national intranet), relying on system services that depend on external server validations introduces a critical Single Point of Failure (SPOF). Android developers operating in such constrained ecosystems must always implement independent fallback mechanisms—like custom HTTP-based downloaders—to guarantee the resilience and stability of their products under any circumstances.</p><p>This article has explored <strong>Why Android DownloadManager Fails on Restricted Networks (Intranet) and How OkHttp Fixes It.</strong> I hope you’ve found it informative and engaging. If you enjoyed this content, feel free to show your support by clapping 👏, following, or leaving a comment below suggesting future topics you’d like to see covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d283bec5b91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Location Selection in MapLibre: 3 Practical Methods]]></title>
            <link>https://medium.com/@mahbooberezaee68/three-methods-for-manual-location-selection-in-maplibre-251253e4bbc4?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/251253e4bbc4</guid>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 05:40:59 GMT</pubDate>
            <atom:updated>2026-02-18T05:26:11.821Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes the GPS has problems and doesn’t work well. The Medium article, <a href="https://medium.com/@mahbooberezaee68/all-you-need-to-know-about-doze-mode-in-android-phones-e10f04bd7764">All You Need To Know About Doze Mode In Android Phones</a> explains this, too. This is a serious issue for fleet drivers because, when GPS is inaccurate, the map does not show the driver’s exact location, and the server cannot detect their location. As a result, drivers may not receive delivery tasks in the app. To solve this, drivers should be able to manually select their correct location on the map and send it to the server, so they can continue working normally until the GPS works properly again. This helps them send their position to the server and keep doing their job in the app normally until the GPS starts working correctly again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*bMjdZZb1CkZE0ySxOJLJkA.png" /><figcaption>Manual Location Selection</figcaption></figure><p>In this article, I want to share my experience at <a href="https://zapexpress.com/"><strong>Alopeyk</strong></a> while implementing manual location selection. I tested several different approaches to find the best solution, and I’m excited to share what I learned. Let’s get started.</p><p>This project features a custom Compose function. I will first explain the function’s logic and then provide the implementation details. The Composable function, SelectedGPSMapScreen, implements a manual location picker using the MapLibre (Tapsi) SDK. To overcome GPS inaccuracies, it allows users to pinpoint their location by manually interacting with the map.</p><p>Next, I will explain how the UI works and describe the design decisions behind it. In manual selection mode, the UI places a custom marker icon at a fixed position in the exact center of the screen using a <em>Box </em>with <em>Alignment.Center</em>. The map itself is rendered underneath this marker and moves as the user pans or zooms. Because the marker remains stationary while the map moves, the user perceives the marker as moving across the map.<br>The location selected by the driver is the point where the marker rests when the interaction stops. To ensure accuracy and operational constraints, the driver must choose a location inside a predefined polygon displayed on the map. Selecting a point outside this polygon is considered invalid, as each driver is required to have a location within their assigned working area in order to receive delivery tasks from the server.</p><p>Before we begin, let me define a few concepts that I will use in this section</p><p>1- <strong>Viewport</strong>: The viewport is the portion of the map that is visible on the screen at any given moment. Imagine the map is infinitely large (with unlimited <em>Lat/Lng</em> coordinates). But on a mobile screen, you only see a small rectangle of that map.</p><h3>Solution 1: Camera Target (<strong>Static Marker UI)</strong></h3><p>The core logic for pinpointing the user’s desired location is handled by the <em>map.addOnCameraIdleListener</em>. As the user interacts with the map and drags it to different areas, the camera coordinates change dynamically. Once the map movement ceases, this listener is triggered, capturing the precise coordinates of the map’s center using the following logic:</p><pre> centerLatLng.value = map.cameraPosition.target</pre><p>To ensure the user remains within the supported zones, the code monitors the <em>state.polygonBorder</em> property. If predefined coordinates are available, the application draws a polygon on the map to visually represent the allowed or active service areas. To improve the user experience, the system utilizes <em>LatLngBounds</em> to calculate the extent of these boundaries, automatically adjusting the camera’s zoom level to ensure the entire polygon is perfectly framed within the screen.</p><p>The final step occurs when the user confirms their choice by clicking the “Select Location” button. At this moment, the application retrieves the current value of <em>centerLatLng.value-representing</em> the exact geographical point located directly beneath the fixed center marker. This data is then transmitted to the ViewModel through the <em>OnCallSendLocationApi</em> event, initiating the backend communication process to save or process the selected location.</p><pre>@Composable<br>fun SelectedGPSMapScreen(<br>    state: FleetInfoContract.State,<br>    effectFlow: Flow&lt;FleetInfoContract.Effect&gt;?,<br>    onEventSent: (event: FleetInfoContract.Event) -&gt; Unit,<br>    navController: NavController,<br>    routeArgs:  Int,<br>) {<br>    val lifecycleOwner = LocalLifecycleOwner.current<br>    val context = LocalContext.current<br>    val mapView = rememberMapViewWithLifecycle(lifecycleOwner, context)<br>    val centerLatLng = remember {<br>        mutableStateOf(<br>            LatLng(<br>                35.748371,<br>                51.378395<br>            )<br>        )<br>    }<br>    ObserveToEffects(<br>        effectFlow = effectFlow,<br>        onEventSent = onEventSent,<br>        navController = navController<br>    )<br><br>    Box(modifier = Modifier.fillMaxSize()) {<br>        AndroidView(<br>            factory = { ctx -&gt;<br>                mapView.apply {<br>                    onCreate(null)<br>                    getMapAsync { map -&gt;<br><br>                        map.uiSettings.isRotateGesturesEnabled = false<br>                        map.uiSettings.isRotateVelocityAnimationEnabled = false<br>                        map.uiSettings.isDisableRotateWhenScaling = true<br><br><br>                        map.addOnCameraIdleListener {<br>                            centerLatLng.value = map.cameraPosition.target!!<br>                        }<br><br>                        map.setStyle(TAPSI_URL) { style -&gt;<br><br><br>                            if (!state.polygonBorder.isNullOrEmpty()) {<br>                                val polygonCoordinates = arrayListOf&lt;LatLng&gt;()<br>                                val boundsBuilder = LatLngBounds.Builder()<br><br>                                state.polygonBorder.forEach {<br>                                    val latLng = LatLng(it.latitude ?: 0.0, it.longitude ?: 0.0)<br>                                    polygonCoordinates.add(latLng)<br>                                    boundsBuilder.include(latLng)<br>                                }<br><br><br>                                map.addPolygon(<br>                                    org.maplibre.android.annotations.PolygonOptions()<br>                                        .fillColor(android.graphics.Color.parseColor(&quot;#802F52E0&quot;))<br>                                        .strokeColor(&quot;#FF2F52E0&quot;.toColorInt())<br>                                        .addAll(polygonCoordinates)<br>                                )<br><br><br>                                val points = polygonCoordinates.map { Point.fromLngLat(it.longitude, it.latitude) }<br>                                val geoJsonSource = GeoJsonSource(&quot;polygon-border&quot;, LineString.fromLngLats(points))<br>                                style.addSource(geoJsonSource)<br><br>                                style.addLayer(<br>                                    LineLayer(&quot;polygon-border-layer&quot;, &quot;polygon-border&quot;).withProperties(<br>                                        PropertyFactory.lineColor(android.graphics.Color.parseColor(&quot;#FF2F52E0&quot;)),<br>                                        PropertyFactory.lineWidth(2f),<br>                                        PropertyFactory.lineCap(Property.LINE_CAP_ROUND),<br>                                        PropertyFactory.lineJoin(Property.LINE_JOIN_ROUND)<br>                                    )<br>                                )<br><br><br>                                val bounds = boundsBuilder.build()<br>                                map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0))<br>                            } else {}<br>                        }<br>                    }<br>                }<br>            },<br>            update = {  },<br>            modifier = Modifier.fillMaxSize(),<br>        )<br><br><br>        Box(modifier = Modifier.fillMaxSize().background(Color.Transparent), contentAlignment = Alignment.Center) {<br>            Row(<br>                modifier = Modifier.fillMaxWidth().padding(top = 16.dp, end = 16.dp).align(Alignment.TopCenter),<br>                horizontalArrangement = Arrangement.End<br>            ) {<br>                Box(<br>                    modifier = Modifier<br>                        .size(44.dp)<br>                        .shadow(7.dp, CircleShape, spotColor = grey_F5F6FF)<br>                        .clip(CircleShape).background(Color.White).padding(10.dp)<br>                        .clickable {}<br>                        .zIndex(1f),<br>                    contentAlignment = Alignment.Center<br>                ) {<br>                    ZapCustomIcon(modifier = Modifier.size(28.dp), id = R.drawable.ic_headset_mic, tint = black_000000)<br>                }<br>            }<br><br>            ZapCustomIcon(modifier = Modifier.size(32.dp, 55.dp), id = R.drawable.ic_marker_manual)<br>        }<br><br>        Row(<br>            modifier = Modifier.fillMaxWidth().background(white).padding(16.dp).align(Alignment.BottomCenter),<br>            verticalAlignment = Alignment.CenterVertically,<br>            horizontalArrangement = Arrangement.spacedBy(8.dp)<br>        ) {<br>            ZapCustomButton(<br>                onClick = {<br>                 },<br>                text = &quot;Select&quot;,<br>                modifier = Modifier.weight(0.70f),<br>                loading = if(routeArgs== 1 ) state.isLoadingChangeStatus else state.isLoading ,<br>                enabled =if(routeArgs== 1 ) !state.isLoadingChangeStatus else !state.isLoading<br>            )<br><br>            OutlinedButton(<br>                modifier = Modifier.weight(0.30f).height(40.dp),<br>                colors = ButtonDefaults.buttonColors(contentColor = black_000000, containerColor = white),<br>                border = BorderStroke(1.dp, black_000000),<br>                shape = RoundedCornerShape(9.dp),<br>                onClick = { }<br>            ) {<br>                Text(&quot;Cancel&quot;, fontFamily = fonts, color = black_000000, fontWeight = FontWeight.W500, fontSize = 12.sp)<br>            }<br>        }<br>    }<br>}</pre><p>The core positioning system relies on the map.cameraPosition.target, which represents the geographic coordinates (LatLng) of the viewport&#39;s exact center. This point is mathematically defined at the pixel coordinates</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*kCe9cjVZhjWOqy7uCpRIhA.png" /></figure><p>marker is typically placed on top of the map, and the application captures whatever coordinate falls directly under this central point once the camera becomes idle.</p><p>However, a primary drawback of this method is Map Inertia. When a user swipes to move the map, the view often continues to glide slightly after the touch is released. This sliding effect makes it frustratingly difficult for users to hit precise boundaries, as the camera target often overshoots the intended location. Consequently, what should be a simple selection task becomes a repetitive process of micro-adjustments to counteract the map’s natural momentum.</p><p>This precision issue is further complicated by a fundamental disconnect between the map engine and the UI layer. Since <em>cameraPosition.target</em> is a fixed mathematical point at the screen’s center, it remains unaware of the visual marker’s dimensions. If a pin icon has any height, its visual tip will never perfectly align with the camera’s theoretical center. Because the map engine does not allow for a manual offset of the camera target — such as shifting it 27dp downward to match a pin’s anchor — a permanent physical offset is created between where the user thinks they are pointing and the coordinate the system actually captures.</p><p>This discrepancy leads to a critical Validation Gap, especially at geographic boundaries. A user may place a marker on the edge of a service polygon and visually confirm it as being inside the allowed area. However, because the captured coordinate is taken from the mathematical center rather than the marker’s visual tip, the <em>Latitude/Longitude</em> might fall just outside the boundary. This creates a confusing experience where the app rejects a location that visually appears to be correct, simply because the eye and the map engine are looking at two different pixels.</p><h3>Solution 2: On-Map Click Selection</h3><p>The <strong>Map-Click method</strong> is technically superior in terms of precision, as it captures the <strong>Exact Interaction Point</strong>. This model provides higher intentionality, ensuring the coordinate is locked precisely where the user touches and preventing the “accidental drift” often seen when maps glide outside geofenced polygons.</p><pre>@Composable<br>fun SelectedGPSMapScreen(<br>    state: FleetInfoContract.State,<br>    effectFlow: Flow&lt;FleetInfoContract.Effect&gt;?,<br>    onEventSent: (event: FleetInfoContract.Event) -&gt; Unit,<br>    navController: NavController,<br>    routeArgs: Int,<br>)<br>{<br>    val lifecycleOwner = LocalLifecycleOwner.current<br>    val context = LocalContext.current<br>    val mapView = rememberMapViewWithLifecycle(lifecycleOwner, context)<br><br>    val selectedLatLng = remember { mutableStateOf&lt;LatLng?&gt;(null) }<br>    val selectedMarker = remember {<br>        mutableStateOf&lt;org.maplibre.android.annotations.Marker?&gt;(null)<br>    }<br><br>    ObserveToEffects(effectFlow, onEventSent, navController)<br><br>    Box(modifier = Modifier.fillMaxSize()) {<br><br>        val bitmap = drawableToBitmap(<br>            context = context,<br>            resId = R.drawable.ic_biker_marker,<br>            sizeDp = 24 <br>        )<br><br>        val icon = IconFactory.getInstance(context).fromBitmap(bitmap)<br><br>        AndroidView(<br>            modifier = Modifier.fillMaxSize(),<br>            factory = {<br>                mapView.apply {<br>                    onCreate(null)<br><br>                    getMapAsync { map -&gt;<br>                        map.uiSettings.isRotateGesturesEnabled = false<br><br>                        map.setStyle(TAPSI_URL) {<br><br>                            map.addOnMapClickListener { point -&gt;<br><br><br><br>                                selectedMarker.value?.remove()<br><br>                                selectedMarker.value = map.addMarker(<br>                                    MarkerOptions()<br>                                        .position(point)<br>                                        .icon(icon)<br><br>                                )<br><br>                                selectedLatLng.value = point<br>                                true<br>                            }<br><br><br>                            if (!state.polygonBorder.isNullOrEmpty()) {<br><br>                                val polygonPoints = arrayListOf&lt;LatLng&gt;()<br>                                val boundsBuilder = LatLngBounds.Builder()<br><br>                                state.polygonBorder.forEach {<br>                                    val latLng = LatLng(<br>                                        it.latitude ?: 0.0,<br>                                        it.longitude ?: 0.0<br>                                    )<br>                                    polygonPoints.add(latLng)<br>                                    boundsBuilder.include(latLng)<br>                                }<br><br>                                map.addPolygon(<br>                                    PolygonOptions()<br>                                        .addAll(polygonPoints)<br>                                        .fillColor(android.graphics.Color.parseColor(&quot;#802F52E0&quot;))<br>                                )<br><br>                                map.moveCamera(<br>                                    CameraUpdateFactory.newLatLngBounds(<br>                                        boundsBuilder.build(),<br>                                        100<br>                                    )<br>                                )<br><br>                                if (selectedLatLng.value == null) {<br>                                    val center = calculatePolygonCenter(polygonPoints)<br><br>                                    selectedMarker.value = map.addMarker(<br>                                        MarkerOptions()<br>                                            .position(center)<br>                                            .icon(icon)<br><br>                                    )<br><br>                                    selectedLatLng.value = center<br>                                }<br><br>                            } else {<br>                                val userLat =<br>                                    locationLive.value?.location?.latitude ?: 35.748371<br>                                val userLng =<br>                                    locationLive.value?.location?.longitude ?: 51.378395<br><br>                                map.moveCamera(<br>                                    CameraUpdateFactory.newLatLngZoom(<br>                                        LatLng(userLat, userLng),<br>                                        14.0<br>                                    )<br>                                )<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        )<br><br>        Row(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .padding(16.dp)<br>                .align(Alignment.TopCenter),<br>            horizontalArrangement = Arrangement.End<br>        ) {<br>            Box(<br>                modifier = Modifier<br>                    .size(44.dp)<br>                    .shadow(7.dp, CircleShape)<br>                    .clip(CircleShape)<br>                    .background(Color.White)<br>                    .clickable {<br>                    },<br>                contentAlignment = Alignment.Center<br>            ) {<br>                ZapCustomIcon(<br>                    modifier = Modifier.size(28.dp),<br>                    id = R.drawable.ic_headset_mic,<br>                    tint = black_000000<br>                )<br>            }<br>        }<br><br>        Row(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .background(white)<br>                .padding(16.dp)<br>                .align(Alignment.BottomCenter),<br>            verticalAlignment = Alignment.CenterVertically,<br>            horizontalArrangement = Arrangement.spacedBy(8.dp)<br>        ) {<br><br>            ZapCustomButton(<br>                modifier = Modifier.weight(0.7f),<br>                text = &quot;Select&quot;,<br>                enabled = selectedLatLng.value != null &amp;&amp;<br>                        if (routeArgs == 1)<br>                            !state.isLoadingChangeStatus<br>                        else<br>                            !state.isLoading,<br>                loading = if (routeArgs == 1)<br>                    state.isLoadingChangeStatus<br>                else<br>                    state.isLoading,<br>                onClick = {<br>                    selectedLatLng.value?.let {<br>                        <br>                    }<br>                }<br>            )<br><br>            OutlinedButton(<br>                modifier = Modifier<br>                    .weight(0.3f)<br>                    .height(40.dp),<br>                shape = RoundedCornerShape(9.dp),<br>                border = BorderStroke(1.dp, black_000000),<br>                colors = ButtonDefaults.buttonColors(<br>                    containerColor = white,<br>                    contentColor = black_000000<br>                ),<br>                onClick = {<br>                }<br>            ) {<br>                Text(<br>                    text = &quot;Cancel&quot;,<br>                    fontFamily = fonts,<br>                    fontSize = 12.sp<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>However, this approach introduces a significant usability challenge: the user’s finger frequently obstructs the view of the exact location at the moment of contact, leading to a “fat finger” problem where the fine details of the map are hidden.</p><p>In a purely click-based interface, if a user misses their target by even a few millimeters, the experience becomes frustrating, as they must repeatedly click to correct the position. In contrast, the <strong>Drag-and-Slide method</strong> offers a far more fluid UI experience. By allowing the user to grab the marker and slide it across the map, the surrounding area remains fully visible. This continuous visual feedback enables the user to maintain context and smoothly align the marker with the desired spot without the need for repetitive, corrective actions.</p><h3>Solution 3 : Projection (Static Marker UI)</h3><p>In this implementation, the location selection process is inverted compared to a standard “Map-Click.” Instead of the user clicking on a static map, a fixed UI marker is anchored at the screen’s center, and the user “moves the map under the marker.” Consequently, a standard click listener is no longer sufficient. To capture the coordinates, the system must rely on the <strong>Map’s Projection</strong>. By utilizing the addOnCameraIdleListener, the app waits for the map to stop moving and then translates the specific pixel coordinates of the screen into geographic Latitude and Longitude.</p><pre>@Composable<br>fun SelectedGPSMapScreen(<br>    state: FleetInfoContract.State,<br>    effectFlow: Flow&lt;FleetInfoContract.Effect&gt;?,<br>    onEventSent: (event: FleetInfoContract.Event) -&gt; Unit,<br>    navController: NavController,<br>    routeArgs: Int,<br>)<br>{<br>    val lifecycleOwner = LocalLifecycleOwner.current<br>    val context = LocalContext.current<br>    val mapView = rememberMapViewWithLifecycle(lifecycleOwner, context)<br><br>    val selectedLatLng = remember { mutableStateOf&lt;LatLng?&gt;(null) }<br>    val mapRef = remember { mutableStateOf&lt;org.maplibre.android.maps.MapLibreMap?&gt;(null) }<br><br>    ObserveToEffects(effectFlow, onEventSent, navController)<br><br>    Box(modifier = Modifier.fillMaxSize()) {<br><br>        AndroidView(<br>            modifier = Modifier.fillMaxSize(),<br>            factory = {<br>                mapView.apply {<br>                    onCreate(null)<br><br>                    getMapAsync { map -&gt;<br>                        mapRef.value = map<br>                        map.uiSettings.isRotateGesturesEnabled = false<br><br>                        map.setStyle(TAPSI_URL) { style -&gt;<br><br>                            if (!state.polygonBorder.isNullOrEmpty()) {<br><br>                                val polygonPoints = arrayListOf&lt;LatLng&gt;()<br>                                val boundsBuilder = LatLngBounds.Builder()<br><br>                                state.polygonBorder.forEach {<br>                                    val latLng = LatLng(<br>                                        it.latitude ?: 0.0,<br>                                        it.longitude ?: 0.0<br>                                    )<br>                                    polygonPoints.add(latLng)<br>                                    boundsBuilder.include(latLng)<br>                                }<br><br>                                map.addPolygon(<br>                                    PolygonOptions()<br>                                        .addAll(polygonPoints)<br>                                        .fillColor(android.graphics.Color.parseColor(&quot;#802F52E0&quot;))<br>                                )<br><br>                                map.moveCamera(<br>                                    CameraUpdateFactory.newLatLngBounds(<br>                                        boundsBuilder.build(),<br>                                        100<br>                                    )<br>                                )<br>                            } else {<br>                                val userLat =<br>                                    locationLive.value?.location?.latitude ?: 35.748371<br>                                val userLng =<br>                                    locationLive.value?.location?.longitude ?: 51.378395<br><br>                                map.moveCamera(<br>                                    CameraUpdateFactory.newLatLngZoom(<br>                                        LatLng(userLat, userLng),<br>                                        14.0<br>                                    )<br>                                )<br>                            }<br><br>                            map.addOnCameraIdleListener {<br>                                selectedLatLng.value = getCenterLatLng(map, mapView)<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        )<br>        Box(<br>            modifier = Modifier<br>                .align(Alignment.Center)<br>                .size(32.dp),<br>            contentAlignment = Alignment.Center<br>        ) {<br>            Image(<br>                painter = painterResource(id = R.drawable.ic_biker_marker),<br>                contentDescription = null<br>            )<br>        }<br><br>        Row(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .padding(16.dp)<br>                .align(Alignment.TopCenter),<br>            horizontalArrangement = Arrangement.End<br>        ) {<br>            Box(<br>                modifier = Modifier<br>                    .size(44.dp)<br>                    .shadow(7.dp, CircleShape)<br>                    .clip(CircleShape)<br>                    .background(Color.White)<br>                    .clickable {<br>                    },<br>                contentAlignment = Alignment.Center<br>            ) {<br>                ZapCustomIcon(<br>                    modifier = Modifier.size(28.dp),<br>                    id = R.drawable.ic_headset_mic,<br>                    tint = black_000000<br>                )<br>            }<br>        }<br><br>        Row(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .background(white)<br>                .padding(16.dp)<br>                .align(Alignment.BottomCenter),<br>            verticalAlignment = Alignment.CenterVertically,<br>            horizontalArrangement = Arrangement.spacedBy(8.dp)<br>        ) {<br><br>            ZapCustomButton(<br>                modifier = Modifier.weight(0.7f),<br>                text = &quot;Select&quot;,<br>                enabled = selectedLatLng.value != null &amp;&amp;<br>                        if (routeArgs == 1)<br>                            !state.isLoadingChangeStatus<br>                        else<br>                            !state.isLoading,<br>                loading = if (routeArgs == 1)<br>                    state.isLoadingChangeStatus<br>                else<br>                    state.isLoading,<br>                onClick = {<br>                    selectedLatLng.value?.let {<br>                        <br>                    }<br>                }<br>            )<br><br>            OutlinedButton(<br>                modifier = Modifier<br>                    .weight(0.3f)<br>                    .height(40.dp),<br>                shape = RoundedCornerShape(9.dp),<br>                border = BorderStroke(1.dp, black_000000),<br>                colors = ButtonDefaults.buttonColors(<br>                    containerColor = white,<br>                    contentColor = black_000000<br>                ),<br>                onClick = {<br>                }<br>            ) {<br>                Text(<br>                    text = &quot;Cancel&quot;,<br>                    fontFamily = fonts,<br>                    fontSize = 12.sp<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>A significant technical challenge arises when using a fixed UI marker: the <strong>Anchor Mismatch</strong>. By default, map engines calculate the cameraTarget based on the exact mathematical center of the viewport. However, users do not perceive the center of the icon as the selection point; instead, they focus on the <strong>bottom tip</strong> of the marker.</p><p>If a marker icon has a height (for example, 55dp), the mathematical center of the screen falls exactly in the middle of the icon. This creates a physical offset equal to half the marker’s height. To the user, the tip of the pin may appear inside a service polygon, but the system — reading from the center — may register the location as “outside.” This creates a frustrating “Validation Gap” where the visual feedback does not match the data being sent to the ViewModel.</p><p>To fix this and make the system match what the user sees, you must calculate the Projection from the <strong>marker’s tip</strong> instead of the screen center. By using projection.fromScreenLocation, you can convert the exact pixel at the bottom of the marker into a LatLng. The formula is simple: take the screen&#39;s center point and add half of the marker&#39;s height to the Y-axis. This way, the calculated coordinates will point exactly to the bottom tip of the icon. Now, the &quot;Inside/Outside&quot; polygon check will be perfectly accurate and match the user&#39;s view.</p><pre>private fun getCenterLatLng(<br>    map: org.maplibre.android.maps.MapLibreMap,<br>    mapView: MapView<br>): LatLng {<br>    val projection = map.projection<br>    val centerPoint = PointF(<br>        mapView.width / 2f,<br>        mapView.height / 2f<br>    )<br>    return projection.fromScreenLocation(centerPoint)<br>}</pre><p>Relying solely on the default <em>cameraTarget </em>is insufficient for a professional-grade manual location picker. The cameraTarget is a rigid mathematical property that remains unaware of UI elements, marker heights, or anchor points. In contrast, the Projection method offers the flexibility to map coordinates to any pixel on the screen. While cameraTarget is easier to implement, it leads to inaccurate data at geofence boundaries; the Projection formula bridges this gap, ensuring that the geographic data is a 1:1 reflection of the UI marker’s tip.</p><p>However, to achieve this 1:1 precision in practice, the getCenterLatLng function must calculate the vertical offset dynamically based on the device’s pixel density. Since physical pixel dimensions vary across different hardware, a hardcoded value, such as 20 pixels, would represent a significant distance on an older device while becoming negligible on a high-resolution modern flagship like the S24.</p><p>This necessity stems from a fundamental unit mismatch: while the UI marker is typically defined in dp (e.g., 32dp), the Projection function and the PointF class operate exclusively in pixels (px). Therefore, to ensure the marker’s tip aligns perfectly with the user’s visual selection across all screen types, you must convert the marker’s dp value into pixels by scaling it according to the screen’s density factor before calculating the final coordinate.</p><pre>private fun getCenterLatLng(<br>    map: org.maplibre.android.maps.MapLibreMap,<br>    mapView: MapView,<br>    context: Context  <br>): LatLng {<br>    val projection = map.projection<br>    val density = context.resources.displayMetrics.density<br>    <br>    val markerHeightDp = 32f <br>    val offsetInPixels = (markerHeightDp * density) / 2<br><br>    val centerPoint = PointF(<br>        mapView.width / 2f,<br>        (mapView.height / 2f) + offsetInPixels <br>    )<br>    <br>    return projection.fromScreenLocation(centerPoint)<br>}</pre><pre>map.addOnCameraIdleListener {<br>    selectedLatLng.value = getCenterLatLng(map, mapView, context)<br>}</pre><p><strong>Final Conclusion</strong></p><p>Synchronizing the mathematical location with the marker’s tip is essential for maintaining system integrity. By accounting for the marker’s height through the Projection formula, we ensure that what the user sees on the screen is exactly what the server receives. For fleet drivers and ambassadors, this level of accuracy is vital; it ensures that even in areas of poor GPS signal, they can manually select their location with confidence. This professional approach ensures that business workflows remain uninterrupted and that geofencing validation remains perfectly accurate.</p><p>This article has explored <strong>Three Methods for Manual Location Selection in MapLibre</strong>. I hope you’ve found it informative and engaging. If you enjoyed this content, feel free to show your support by clapping <strong>👏</strong>, following, or leaving a comment below suggesting future topics you’d like to see covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=251253e4bbc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Android App Size: Best Practices for Developers]]></title>
            <link>https://medium.com/@mahbooberezaee68/optimizing-android-app-size-best-practices-for-developers-07c2b7cc25fb?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/07c2b7cc25fb</guid>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 14:47:05 GMT</pubDate>
            <atom:updated>2025-12-31T14:47:05.149Z</atom:updated>
            <content:encoded><![CDATA[<p>Don’t let a large file size stand between your app and its users. In areas with spotty internet or expensive data, a smaller app means more downloads. Follow this walkthrough to compress your build and improve your conversion rates globally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*K9cqTDo_KHvPC74tOxFEqg.png" /></figure><p>Our primary objective is to explore effective strategies for optimizing and reducing our APK footprint.</p><h3>Understand the APK structure</h3><p>To understand how to reduce your app’s size, you first need to look inside the APK (Android Package Kit). An APK is essentially a ZIP file that contains everything your app needs to run. The best way to see this is using the <strong>APK Analyzer</strong> built into Android Studio:</p><p>Go to Build &gt; Analyze APK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*U5Lq9wIhicYo67JONI2WJQ.png" /></figure><p>After that, select your generated .apk file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*BaUuLQPxiWF5gx7HWOlqRQ.png" /></figure><p>Finally, the Output is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDCijTQrXJt4oarPl-tPJQ.png" /></figure><h4>1. classes.dex</h4><p>This is where your Java or Kotlin code lives. Since Android doesn’t run .class files directly, your code is compiled into Dex (Dalvik Executable) files. If your app is large, you might see classes2.dex or classes3.dex due to the 64k method limit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCfgqBgLWjUYaevr-5qUcQ.png" /></figure><h4>2. lib/</h4><p>This contains compiled native code directed at specific processor architectures (ABIs).</p><p>armeabi-v7a: For older 32-bit ARM processors.</p><p>arm64-v8a: For modern 64-bit ARM processors.</p><p>x86 / x86_64: Mostly for emulators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlT59Wdo8Y9C2d13MjoDyQ.png" /></figure><h4>3. assets/</h4><p>Unlike the res/ folder, files here are kept in their raw format. Developers use this for:</p><ol><li>Custom fonts (.ttf).</li></ol><p>2. Database files or bundled JSON data.</p><p>3. Game textures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HD1oCToSnI-bfD6fJ9PIwA.png" /></figure><h4>4. AndroidManifest.xml</h4><p>Every APK must have this. It defines the app’s package name, permissions, activities, services, and hardware requirements. In the APK, this is stored in a compressed binary XML format to save space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUHo1iZ_ro5730flK0a5Tw.png" /></figure><h4>5. resources.arsc</h4><p>This is the Resource Table. It contains all the compiled XML content (like strings or colors) and links the resource IDs in your code to the actual values or file paths in the res/ folder.</p><h4>6. res/</h4><p>This folder contains all the resources that aren’t compiled into resources.arsc. This includes:</p><ol><li>Drawables: Images (PNG, JPEG, WebP).</li></ol><p>2. Layouts: XML files for your UI.</p><p>3. Menu/Values: Other UI-related XMLs.</p><h4>7. META-INF/</h4><p>This folder holds the “proof” that your app is authentic. It contains the signing certificates and a manifest of checksums for every file in the APK to ensure the code hasn’t been tampered with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZGsJATmRQdVwcQ3fGUYaQ.png" /></figure><h3>Minimizing Library Resource Usage</h3><p>When building an Android app, you often use external libraries to add more features and improve the user experience.</p><h4>1. Remove unused libraries</h4><p>Identify and eliminate ghost dependencies, libraries that are declared but never referenced. Removing these redundant dependencies is a crucial step in preventing APK bloat and keeping your build clean. Additionally, enabling shrinkResources in your Gradle build script allows the compiler to automatically identify and strip away unused resources from bundled libraries.</p><pre>android {<br>    buildTypes {<br>        release {<br>            minifyEnabled true   // Removes unused code<br>            shrinkResources true // Removes unused library resources<br>            proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;<br>        }<br>    }<br>}</pre><p>Code shrinking is great for cleaning up libraries, but it isn’t always enough to remove large, built-in dependencies.</p><h4>2. Using Gradle Exclusions to Minimize APK Size</h4><p>Many libraries include additional sub-libraries and resources that your project may not actually require. These are known as transitive dependencies, and they can silently bloat your APK. To optimize your build, you should explicitly exclude these redundant modules within your dependency declarations. For example, if you are using a specific utility but want to avoid pulling in an unnecessary pager module, you can refine your implementation like this:</p><pre>implementation(&quot;com.google.accompanist:accompanist-systemuicontroller:0.32.0&quot;) {<br>        exclude module: &quot;accompanist-pager&quot;<br>    }</pre><h3>Optimizing Images:</h3><h4>1. Convert PNG to WebP</h4><p>Large images can quickly increase your APK size. To keep your app lean, you should convert your images to more efficient formats. WebP is a modern image format that provides superior compression. It can significantly reduce file size without losing quality.</p><p>Right-click your PNG file in Android Studio and select <strong>Convert to WebP</strong>. So you get a much smaller file that looks identical to the original.</p><h4>2. Convert PNG to Vector Assets (XML)</h4><p>For icons and simple illustrations, using XML (Vector Drawables) is better than using PNGs. Vectors are tiny in size and stay sharp at any resolution.</p><p>Go to <strong>File &gt; New &gt; Vector Asset</strong>. You can import SVG files or choose from Material icons. Instead of having multiple PNG files for different screen densities (mdpi, hdpi, xhdpi), you only need one small XML file.</p><h4>3. Don’t Use Material Icon Dependency</h4><p>Avoid adding the full Material Icons dependency. Instead, export individual icons from Figma as SVGs. This ensures your APK stays lean by only including the specific assets your design requires.</p><h3>Optimizing Native Binaries with ABI Filters</h3><p>If you use heavy libraries like <strong>MapLibre</strong>, <strong>Mapbox</strong>, or any specialized SDK that relies on native code (C++), your APK size can skyrocket. This is because these libraries include separate files for every CPU architecture (ABIs), including those only used by simulators. By default, your APK contains native libraries for various architectures like x86 and x86_64 (mostly for emulators) and armeabi-v7a, arm64-v8a (for real physical devices). To optimize the production build, you can filter out the architectures you don&#39;t need. Add this block to your app/build.gradle:</p><pre>android {<br>    defaultConfig {<br>        ndk {<br>            // Include only the architectures used by real Android devices<br>            // This removes x86 and x86_64 (used mainly for simulators)<br>            abiFilters &quot;armeabi-v7a&quot;, &quot;arm64-v8a&quot;<br>        }<br>    }<br>}</pre><p>Libraries like MapLibre contain large .so files. Removing the simulator-specific binaries (x86) can often reduce your APK size by <strong>10MB to 30MB</strong> or more.</p><p>Keep in mind that after adding these filters, your app might not run on some standard computer emulators (which use x86). However, it will work perfectly on all modern physical Android phones.</p><h3>Optimizing Language Resources</h3><p>Many third-party libraries come with localized resources for dozens of languages. For example, even if your app only supports English and Persian, your final APK might still contain strings for French, Russian, or Japanese just because a library you use supports them.</p><p>You can use resConfigs to tell the build system which languages you actually want to keep. This will automatically strip away all other language-specific strings and resources from every library in your project.</p><p>Add this line to your app/build.gradle:</p><pre>android {<br>    defaultConfig {<br>        // Keeps only English and Persian resources<br>        // All other language strings from libraries will be removed<br>        resConfigs &quot;en&quot;, &quot;fa&quot;<br>    }<br>}</pre><p>This removes hundreds of unused <strong>string.xml</strong> files and other localized assets from libraries like Google Play Services or Material Components.</p><h3>Don’t Over-complicate Your Dependency Graph</h3><p>Avoid adding external libraries for components that are already part of your design system. For instance, if you’re using Material 3, leverage its built-in components like PullToRefreshBox instead of adding a separate, redundant SwipeRefresh library.</p><h4>Remove unused files in your project</h4><p>You can easily scan your project to find and delete unused files</p><p>At <a href="https://zapexpress.com/"><strong>Alopeyk Company</strong></a>, we have successfully implemented these optimization techniques, significantly reducing our APK footprint while maintaining a high-performance experience for our users. The following analysis illustrates the impact of these optimizations on our final build size.</p><h4>Result</h4><p>As shown in the attached analysis, our optimization efforts led to a significant reduction in the APK footprint. You can review the detailed breakdown of the results in the following images.</p><p>Our initial analysis of the APK (v3.5.0) shows a total size of 64.7 MB. The largest portion belongs to native libraries (15.2 MB download size). By identifying these heavy components, we were able to apply the optimization techniques mentioned above to achieve a much leaner build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yvt0V8UZZZ4f-C2GMvC_Kw.png" /></figure><p>As shown in the analysis, we successfully reduced the total APK size from <strong>64.7 MB</strong> to <strong>29.7 MB</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*mdDeWIQkZcNaQfHyO2eF0A.png" /><figcaption>Impact Analysis: Achieving a 54% Reduction in APK Size</figcaption></figure><p>This article has explored <strong>Optimizing Android App Size: Best Practices for Developers.</strong> I hope you’ve found it informative and engaging. If you enjoyed this content, feel free to show your support by clapping <strong>👏</strong>, following, or leaving a comment below suggesting future topics you’d like to see covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07c2b7cc25fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Safety Navigation in Jetpack Compose]]></title>
            <link>https://medium.com/@mahbooberezaee68/type-safety-navigation-in-jetpack-compose-bbd5b9a0a72f?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbd5b9a0a72f</guid>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 14:02:16 GMT</pubDate>
            <atom:updated>2025-12-20T05:52:47.813Z</atom:updated>
            <content:encoded><![CDATA[<p>With <a href="https://developer.android.com/guide/navigation/design/type-safety">Jetpack Navigation 2.8.0, the type-safe navigation APIs</a> in Kotlin are now stable. You can define destinations using serializable types and get compile-time safety. This is especially good for Jetpack Compose, making it easier and safer to set up navigation destinations and arguments. I want to be To enhance stability and developer experience, to enhance stability and developer experience, we at <a href="https://zapexpress.com/"><strong>Alopeyk Company</strong></a> have decided to migrate our current string-based routing system to Type-Safe Navigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*4_HxCxWfLWPgZMPueeP8Zg.png" /></figure><p>Before type-safe navigation, compose relied on manually crafted string routes. Developers had to build routes by hand, insert parameters into them, and parse those values on the destination side. <strong>Type-Safe Navigation isn’t about app performance; it’s about saving the developer’s sanity</strong> 😄. We’ll start this article by examining the drawbacks of string-based navigation.</p><h3>String-Based Navigation with multiple drawbacks:</h3><p>String-based navigation relies on manually constructed route strings to pass destinations and arguments, making it prone to errors and difficult to maintain. For example, home/123 represents a string that contains the route along with its parameter.</p><pre>// Navigating to a home screen with an ID<br>navController.navigate(&quot;home/123&quot;)</pre><p><strong>1.</strong> <strong>Lack of Type Safety: </strong>Parameters are passed as raw strings. If a destination expects an Int but receives a String, this mismatch won’t be detected at compile time; only at runtime leading to potential crashes.</p><pre>// Extracting the ID from the route string<br>val profileId = backStackEntry.arguments?.getString(&quot;id&quot;)?.toIntOrNull() ?: 0</pre><p><strong>2.</strong> <strong>Manual String Construction: </strong>Developers had to join and insert strings by hand to make routes, which could cause errors if the format was wrong</p><pre>// Incorrectly formatted route<br>val userId = &quot;123&quot; navController.navigate(&quot;home/userId&quot;) // Should be &quot;$userId&quot;</pre><p>These problems were common, especially in large applications that had many parameters, which made the navigation logic prone to errors and more difficult to maintain.</p><p><strong>3.</strong> <strong>Runtime Errors: </strong>Because navigation routes were written as strings, mistakes in route names or parameter types were only found when the app ran, which made debugging hard.</p><pre>// Incorrect route name<br>navController.navigate(&quot;hume/123&quot;)</pre><p>This error would only appear at runtime, making it harder to detect and fix.</p><p><strong>4.</strong> <strong>Limited Scalability: </strong>As apps became more complex, handling many routes and parameters as strings became difficult and prone to mistakes. This was especially hard when managing navigation across different modules or features.</p><p>The new API allows routes and parameters to have explicit types. The navigation system now knows the type of each parameter and can check it at compile time.</p><p>Moving from string-based navigation to type-safe navigation is one of the biggest enhancements in Jetpack Compose Navigation starting from version 2.8.0. In the first step, we compare two approaches. Afterward, I explain how type-safe navigation works.</p><h4><strong>Compile Time Safety</strong></h4><p>In the string-based approach, you would define routes like “profile/{userId}”. If you made a typo (e.g., “profile”), the app would compile successfully without any errors, but it would crash at runtime during navigation. In Type-safe navigation, routes are defined using classes or objects. If you misspell a class name, the IDE flags the error immediately and prevents the app from compiling.</p><h4>Arguments Handling</h4><p>Previously, you had to manually concatenate arguments into strings and then parse and cast them back at the destination. With the Type-safe method, you use a Data Class. The library performs automatic serialization and deserialization, allowing you to pass a full object and receive it on the other side with all types preserved.</p><h4>Refactoring</h4><p>Suppose you want to rename a route or add a new parameter. In String-based, you would have to search for all string occurrences throughout the project and update them manually, which is highly error-prone. In Type-safe<strong>,</strong> you simply rename the class or the field. Thanks to Kotlin’s powerful refactoring capabilities, every part of the project using that route will either be updated automatically or trigger a compile-time error to guide your corrections.</p><h4>Maintenance</h4><p>In the string-based approach, as the project grows, managing hundreds of interdependent strings becomes a nightmare. Even a small change in a single parameter can trigger a chain of crashes. With the type-safe approach, since your source of truth is a class, changes are applied at a single point. If you remove a parameter, the compiler flags every place where it is used so you can fix it. This makes the project much more predictable and easier to maintain.</p><h4>Readability</h4><p>String-based code often looks cluttered and ‘dirty’ due to the constant use of slashes, curly braces, and manual null checks. In Type-safe navigation,<em> </em>routing code looks exactly like calling a function or instantiating a standard Kotlin object. Anyone reading the code can immediately identify what data (and in what format) a screen requires, without needing to jump to the destination code to figure out what a specific string is supposed to be cast into.</p><p>Additionally, when you use objects, features such as autocomplete and find usages function correctly. You can clearly see which parameters each screen requires and where they are used.</p><h3>How Does Type Safety Navigation Work?</h3><p>In type safety navigation, you no longer need to concatenate strings or worry about formatting errors manually. Errors such as passing the wrong type or misspelling an argument are prevented before the app even runs.</p><p>To use them, add <a href="https://developer.android.com/guide/navigation#kts">Jetpack Navigation version 2.8.0 or later and the Kotlin serialization plugin</a> to your project.</p><pre>plugins {<br>  // Kotlin serialization plugin for type safe routes and navigation arguments<br>  kotlin(&quot;plugin.serialization&quot;) version &quot;2.0.21&quot;<br>}<br><br>dependencies {<br>  val nav_version = &quot;2.9.6&quot;<br><br>  // Jetpack Compose integration<br>  implementation(&quot;androidx.navigation:navigation-compose:$nav_version&quot;)<br> <br>  // JSON serialization library, works with the Kotlin serialization plugin<br>  implementation(&quot;org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0&quot;)<br>}</pre><h4>Use the following guidelines to choose the appropriate type for your route:</h4><p><strong>- Object:</strong> Use an object for routes that do not require any arguments.</p><p><strong>- Class or Data Class:</strong> Use a class or data class for routes that have arguments.</p><p><strong>- KClass&lt;T&gt;:</strong> Use this when you don’t need to pass arguments, such as a class without parameters or a class where all parameters have default values.</p><p>For example:</p><pre>// Define a home route that doesn&#39;t take any arguments<br>@Serializable<br>object Home<br><br>// Define a profile route that takes an ID<br>@Serializable<br>data class Profile(val id: String)</pre><h3>Build your Navigation</h3><p>Next, you need to define your navigation graph. Because we use Kotlinx Serialization, the navigation system must handle every route the same way. By defining BaseRoute, we have essentially created a Marker Interface. The role of this marker is to collect and unify all our application’s navigation routes into a single, cohesive category.</p><pre>interface BaseRoute</pre><p>Second, you need to create a Kotlin file named GraphRoute and list all your graphs and subgraphs in your project, like this</p><pre>@Serializable<br>object HomeGraph: BaseRoute<br>@Serializable<br>object PromotionGraph: BaseRoute<br><br>@Serializable<br>object ShiftGraph: BaseRoute<br><br>@Serializable<br>object ProfileGraph: BaseRoute<br><br>//Profile Sub Graph<br>@Serializable<br>object ClubGraph: BaseRoute<br><br>@Serializable<br>object ReportGraph: BaseRoute<br><br>@Serializable<br>object BoxStatusGraph: BaseRoute<br><br>@Serializable<br>object WorkingPlanGraph: BaseRoute<br><br>.<br>.<br>.</pre><p>You consider each feature as an independent navigation graph. This structure is named <strong>Feature-level Navigation. </strong>You can see my navGraph structure. This structure perfectly aligns with the principles of a Scalable Navigation Architecture.</p><pre>navGraph/<br> └─ safetyNavigation/<br>     ├─ navigation/   → NavGraphBuilder<br>     ├─ route/        → Route (Screens)<br>     ├─ base/         → BaseRoute<br>     └─ Graph         → Graphs and Sub Graphs</pre><p>One example for the route, HomeRoute Kotlin file</p><pre><br>import kotlinx.serialization.Serializable<br><br>@Serializable<br>object HomeRoute: BaseRoute<br><br>@Serializable<br>object DispatchRoute: BaseRoute</pre><p>The structure we’ve implemented adheres to several key principles of clean and scalable application architecture:</p><p><strong>- Routes are Fully Isolated Within the Graph</strong></p><p><strong>- Dependencies are Transparent</strong></p><p><strong>- Root Graph Defines the Feature Boundary</strong></p><p>The SetupNavHost composable function serves as the <strong>central router</strong> for the entire application, defining the complete navigation tree. It configures the navhost to start at the HomeGraph and then registers all major feature flows (like HomeGraph, ProfileGraph, ShiftGraph) and various sub-graphs as distinct, modular destinations.</p><pre>@Composable<br>fun SetupNavHost(navController: NavHostController, viewModel: NewDispatchViewModel) {<br>    NavHost(<br>        navController = navController,<br>        startDestination = HomeGraph::class,<br>    ) {<br>        // BottomNav Graph<br>        homeGraph(navController, viewModel)<br>        profileGraph(navController)<br>        promotionGraph(navController)<br>        shiftGraph(navController)<br>        // Profile sub graph<br>        workingPlaneGraph(navController)<br>        walletGraph(navController)<br>        reportGraph(navController)<br>        ticketGraph(navController)<br>        boxGraph(navController)<br>        clubGraph(navController)<br>    }<br>}</pre><p>Now, we need to construct a Navigation Graph, and we will use the NavGraphBuilder to define its structure. NavGraphBuilder is the tool that allows you to construct a NavGraph and specify its contents. It is, in fact, responsible for building the main navigation container. A NavGraph represents a complete collection of accessible destinations within a section of your application.</p><pre>  private fun NavGraphBuilder.homeGraph(navController: NavHostController) {<br>        navigation&lt;HomeGraphRoute&gt;(<br>            startDestination = HomeRoute<br>        ) {<br>            composable&lt;HomeRoute&gt; {<br>                val viewModel: HomeViewModel = hiltViewModel()<br>                HomeScreen(<br>                    uiState = viewModel.uiState.collectAsState().value,<br>                    event = viewModel::onEvent,<br>                    navController = navController,<br>                    effect = viewModel.effect,<br>                )<br>            }<br>             composable&lt;DispatchRoute&gt; {<br>                val viewModel: DispatchViewModel = hiltViewModel()<br>                DispatchScreen(<br>                    uiState = viewModel.uiState.collectAsState().value,<br>                    event = viewModel::onEvent,<br>                    navController = navController,<br>                    effect = viewModel.effect,<br>                )<br>            }<br><br>}</pre><p>The HomeGraphRoute object serves as the architectural container for everything related to the main home feature. It clearly defines what belongs inside (the routes and logic) and what remains outside, thereby enforcing strong feature isolation.</p><p><strong>Data Transfer in Type-Safe Navigation</strong></p><p>You should pass small, simple data types such as primitives and enums between screens. Do not pass large objects, complex lists, or entire models, as the navigation system is optimized only for handling lightweight, serializable data.</p><p><strong>SharedViewModel In Type-Safe Navigation</strong></p><p>In scenarios requiring shared state across multiple screens, you often utilize a Shared ViewModel. In the standard Android Navigation setup, such a ViewModel is typically scoped to a parent navigation graph, allowing it to be retrieved from the back stack. While this concept is detailed in the article ‘<a href="https://medium.com/@mahbooberezaee68/retrieving-viewmodels-within-navigation-graphs-jetpack-compose-4eb5a1293d25">Retrieving ViewModels Within Navigation Graphs</a>,’ I have developed a new utility function that simplifies retrieving this shared ViewModel using the BaseRoute type.</p><pre>@Composable<br>inline fun &lt;reified T : ViewModel&gt; NavBackStackEntry.sharedViewModel(<br>    navController: NavController,<br>    navGraphRoute: BaseRoute,<br>    navBackStackEntry: NavBackStackEntry<br>): T {<br>    val parentEntry = remember(navBackStackEntry) {<br>        navController.getBackStackEntry(navGraphRoute)<br>    }<br><br>    return hiltViewModel(parentEntry)<br>}</pre><p>Now use sharedViewModel</p><pre>  composable&lt;PromotionHistoryRoute&gt; {<br>            val previousBackStackEntry = remember { navController.previousBackStackEntry }<br>            val viewModel = previousBackStackEntry!!.sharedViewModel&lt;ClubViewModel&gt;(<br>                navController,<br>                previousBackStackEntry.toRoute&lt;CurrentPromotionRoute&gt;(),<br>                previousBackStackEntry)<br>             PreviousPenalizeScreen(<br>                uiState = viewModel.viewState.value,<br>                effectFlow = viewModel.effect,<br>                onEventSent = { event -&gt; viewModel.setEvent(event) },<br>                navController = navController<br>            )<br>        }</pre><p>This article has explored <strong>Type Safety Navigation in Jetpack Compose.</strong> I hope you’ve found it informative and engaging. If you enjoyed this content, feel free to show your support by clapping <strong>👏</strong>, following, or leaving a comment below suggesting future topics you’d like to see covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbd5b9a0a72f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Doze Mode Affects Location Providers]]></title>
            <link>https://medium.com/@mahbooberezaee68/how-doze-mode-affects-location-providers-392a499c03eb?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/392a499c03eb</guid>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 08:32:21 GMT</pubDate>
            <atom:updated>2025-12-06T14:43:46.671Z</atom:updated>
            <content:encoded><![CDATA[<p>Android offers multiple location providers such as GPS, Network, and the Fused Location Provider that each delivering different levels of accuracy, power usage, and responsiveness. Understanding how these providers behave under system constraints like Doze Mode is essential for building reliable, energy-efficient location tracking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTVqy0tF4okCMRKZFuBiVA.png" /></figure><p>We previously published an article about <a href="https://medium.com/@mahbooberezaee68/all-you-need-to-know-about-doze-mode-in-android-phones-e10f04bd7764?postPublishedType=repub">Doze Mode</a> during our time at <a href="https://zapexpress.com/"><strong>Alopeyk Company</strong></a>, where we explored the challenging issues related to background location tracking and Android’s power-management constraints. As discussed in those earlier write-ups, <a href="https://developer.android.com/training/monitoring-device-state/doze-standby?utm_source=chatgpt.com">Android’s Doze Mode (introduced in Android 6.0)</a> aggressively restricts background operations, often disrupting Location Providers and preventing reliable background location updates.</p><p>In this new article, we take a deeper look at how Doze Mode specifically impacts Fused Location Provider (FLP) and other location APIs. We will break down the exact behavioral changes, explain why apps lose location accuracy or stop receiving updates, and outline the essential steps required to maintain stable, predictable, and real-time location tracking even when the device enters Doze.</p><p>Doze Mode restricts CPU, network, alarms, and background tasks when the device is idle. This creates the following behavior in location APIs:</p><h3>GPS Provider</h3><p><a href="https://developer.android.com/training/monitoring-device-state/doze-standby?utm_source=chatgpt.com">The GPS Provider is fully disabled during Doze Mode</a>. When the device enters Doze, Android completely stops all GPS hardware activity, meaning the system no longer performs satellite scanning or attempts to acquire a GPS fix. As a result, apps receive no GPS updates at all until the device exits Doze or the user wakes the device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAjrJbtKwLX3hqZtiv_jsw.png" /></figure><h3>Network Provider</h3><p><a href="https://developer.android.com/training/monitoring-device-state/doze-standby?utm_source=chatgpt.com">The Network Provider remains partially active during Doze</a>, but its performance is significantly degraded. Android aggressively throttles all network-assisted location<strong> </strong>sources, meaning your app receives fewer and less reliable updates. Wi-Fi scanning is almost entirely suppressed, eliminating the high-accuracy signals normally used for network positioning. As a result, the system may occasionally fall back to cell-tower–based coarse location, but accuracy is low and updates are infrequent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfzwgf7PiD0jmR0B1gPYjA.png" /></figure><h3>Passive Providers</h3><p>Still works, but only receives updates when another app or system component requests location. It does not cause any scanning itself.</p><h3>FusedLocationProvider (FLP)</h3><p>Fused Location Provider combines GPS, Wi-Fi, cell towers, and sensors to produce location. When the device enters Doze Mode, Android heavily restricts all these components.</p><h4><strong>- Background FLP Updates:</strong></h4><p>When your app is in the background, completely blocked ☹</p><p>· No location updates are delivered</p><p>· All FLP requests are deferred</p><p>· GPS, Wi-Fi, and sensor updates are suspended</p><p>· Nothing is queued or stored</p><p>FLP is the most affected by Doze. <a href="https://developer.android.com/develop/sensors-and-location/location/battery?utm_source=chatgpt.com"><strong><em>It stops giving background updates in Doze</em></strong></a><strong><em>; only foreground service requests keep working.</em></strong></p><h4><strong>- Foreground Service FLP</strong></h4><p>Even if you run a foreground service, it does not bypass Doze completely</p><p>· You will still receive delayed updates</p><p>· Update frequency is lower than requested</p><p>· Android prevents continuous GPS scanning</p><h3><strong>High Accuracy (GPS-based) Requests</strong></h3><p>When using <strong>Priority.PRIORITY_HIGH_ACCURACY </strong>, GPS cannot run continuously under Doze.</p><p>· Turn GPS on/off intermittently</p><p>· Reduce how often satellite scans happen</p><p>· Delay GPS fixes significantly</p><p>Strongly Throttled.</p><h3>Low-power FLP Requests</h3><p>Requests such as <strong>Priority.PRIORITY_BALANCED_POWER_ACCURACY</strong> or <strong>Priority.PRIORITY_LOW_POWER</strong> will still work, but:</p><p>· With low accuracy</p><p>· With long intervals</p><p>· Not suitable for real-time tracking</p><p>Low-power modes work better, but not reliably. So, Allowed but Infrequent</p><h3>FLP Cannot Acquire WakeLocks in Doze</h3><p>In Doze Mode, Android blocks apps from holding wake locks. So FLP <strong>cannot</strong> keep the CPU or GPS awake.</p><h3>Only Three Ways FLP Works Properly in Doze</h3><h4>1- Battery Optimization Disabled (Whitelisted App):</h4><p>When the user grants “Ignore Battery Optimizations” permission, all Doze Mode restrictions are lifted for that app. So,</p><p>· FLP works normally</p><p>· GPS can stay active</p><p>· Updates arrive with full accuracy</p><h4>2- Active Navigation Scenario</h4><p>Doze does <em>not</em> activate when:</p><p>· The user is navigating (e.g., Maps, Waze)</p><p>· The screen is on</p><p>· Motion sensors detect movement</p><p>Apps like Google Maps avoid Doze automatically during navigation.</p><h4>3- High-Priority FCM Message Wakes the Device</h4><p>High-priority Firebase messages can useful for periodic updates, not continuous tracking.</p><p>· Temporarily wake the app</p><p>· Allow one quick location request</p><p>· Then the device returns to Doze</p><p>Doze Mode is one of the biggest obstacles in designing reliable tracking systems on Android.<br> Understanding how each Location Provider behaves under Doze helps prevent:</p><ul><li>Unexpected gaps in tracking</li><li>Delayed location updates</li><li>Incorrect coarse positions</li><li>Complete loss of background updates</li></ul><p>This article has explored <strong>How Doze Mode Affects Location Providers.</strong> I hope you’ve found it informative and engaging. If you enjoyed this content, feel free to show your support by clapping <strong>👏</strong>, following or leaving a comment below suggesting future topics you’d like to see covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=392a499c03eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All You Need To Know About Doze Mode In Android Phones]]></title>
            <link>https://medium.com/@mahbooberezaee68/all-you-need-to-know-about-doze-mode-in-android-phones-e10f04bd7764?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/e10f04bd7764</guid>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 10:45:47 GMT</pubDate>
            <atom:updated>2025-12-15T11:23:35.553Z</atom:updated>
            <content:encoded><![CDATA[<p>While working at <a href="https://zapexpress.com/"><strong>Alopeyk Company</strong></a>, I encountered a challenging issue related to location handling, specifically when dealing with Android’s Doze Mode. During my investigation, I gathered a set of valuable insights and practical solutions. I decided to turn this knowledge into some articles and share it so others can benefit from it as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-Z8ShPRjpta9VxQkUbSGw.png" /></figure><p><strong>Doze Mode</strong> is a battery-saving mechanism in Android that was introduced in Android 6.0 (Marshmallow). Its purpose is to limit the background activity of apps when the device is left unused for a long period, with the screen off and no motion detected, helping to reduce power consumption.</p><p><strong>When does Doze activate?</strong></p><p>Doze typically activates when a combination of conditions is met, including:</p><ul><li>The device is <strong>not plugged in</strong> (unplugged).</li><li>The screen is <strong>off</strong>.</li><li>The device has been <strong>stationary</strong> (no movement).</li><li>No long-term <strong>wake lock</strong> has been held by apps.</li></ul><p>This combination ensures that Doze only activates when the device is truly idle - not when the user is actively using it or simply carrying it in their pocket.</p><p>You can see doze state flow chart</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*nKHOl_BdcVnQhkfqQz4Ozg.png" /><figcaption>Doze State Flow Chart</figcaption></figure><h3><strong>What Happens in Doze Mode?</strong></h3><p>Android introduced Doze Mode in Android 6.0 (Marshmallow) to improve battery life by restricting background CPU and network activities when the device is idle. One of the most important mechanisms inside Doze Mode is the Maintenance Window.</p><p><strong>CPU &amp; Network — are paused most of the time</strong></p><ul><li>The processor (CPU) only wakes up occasionally.</li><li>The network (WiFi/data) is usually disconnected.</li><li>It becomes active again only during the <strong>maintenance window</strong>.</li></ul><p><strong>WakeLocks — are ignored (except during the maintenance window)</strong></p><p>A wakeLock means you force the CPU to stay awake.</p><ul><li>In doze mode wakeLocks basically do not work.</li><li>They are only effective during the short <strong>maintenance window</strong>.</li></ul><p><strong>Alarms — are deferred</strong></p><ul><li>App alarms (AlarmManager) do not run at the exact scheduled time.</li><li>The system postpones them until the next Doze wake-up.</li><li>Only <strong>high-priority alarms</strong>, such as <strong>AlarmClock</strong>, will fire on time.</li></ul><p><strong>Jobs &amp; Sync — remain paused until the maintenance window</strong></p><ul><li><strong>WorkManager / JobScheduler</strong> will not run until the next Doze maintenance window begins.</li><li>Background sync operations (like <strong>SyncAdapter</strong>) are completely paused.</li></ul><p>The diagram illustrates when a scheduled job runs during Doze mode:</p><pre>Scheduled Job  ──────────────┐<br>                             v<br>| ---- Doze Sleep ---- | Maintenance Window | ---- Sleep ---- |<br>                           ↑<br>                     Job executed here</pre><p><strong>1.Doze Sleep</strong></p><ul><li>When the device is in Doze, most background tasks are paused.</li><li>Scheduled jobs cannot run, the CPU may be asleep, and the network is off.</li></ul><p><strong>2.Maintenance Window</strong></p><ul><li>Periodically, Android wakes the device briefly for a <strong>maintenance window</strong>.</li><li>During this short time, scheduled jobs (JobScheduler or WorkManager) are allowed to execute.</li></ul><p><strong>3.Job Execution</strong></p><ul><li>The arrow in the diagram shows that the <strong>job runs only during the maintenance window</strong>.</li><li>After the window ends, the device goes back to sleep until the next maintenance window.</li></ul><p>Scheduled jobs don’t run continuously in Doze; they wait for the maintenance window. This design ensures apps can complete background tasks without draining battery.</p><p><strong>Network</strong> — Disabled except during maintenance</p><ul><li>Apps are not allowed to use the network.</li><li>The network is only active during short maintenance windows.</li><li>Network requests are queued</li></ul><p>The diagram shows network behavior during Doze mode:</p><pre>|---------- No Network ---------| Net ON |---- No Network ----|<br>                                ↑<br>                         Maintenance Window</pre><ol><li><strong>No Network (Doze)</strong></li></ol><ul><li>Before the maintenance window, the network is completely off.</li><li>Apps cannot send or receive any data, and all network operations are paused.</li></ul><p><strong>2. Network ON (Maintenance Window)</strong></p><ul><li>During the maintenance window (marked by the arrow), the system temporarily enables the network.</li><li>Apps can perform short network tasks like syncing data, sending/receiving FCM notifications, or running scheduled jobs.</li></ul><p><strong>3. Back to No Network</strong></p><ul><li>After the maintenance window ends, the network is turned off again until the next window.</li><li>This cycle repeats periodically, with the gaps between windows increasing the longer the device stays in Doze, to save battery.</li></ul><p>The network is only available during the short maintenance window, which is why apps must schedule network operations to run at these times (via JobScheduler, WorkManager, etc.).</p><p><strong>GCM/Firebase Push</strong> — Delivered only during maintenance window</p><ul><li>Firebase (FCM) notifications with <strong>normal priority</strong> are <strong>not delivered immediately</strong>.</li><li>They are delivered <strong>once the device enters the maintenance window</strong>.</li><li>However, <strong>high-priority FCM</strong> (e.g., urgent chat messages) <strong>still bypass Doze</strong>.</li></ul><p>Almost nothing runs. The device wakes up only for short periods of a few minutes to:</p><ul><li>Deliver normal-priority pushes</li><li>Execute jobs</li><li>Perform syncs</li><li>Process alarms</li><li>Temporarily enable the network</li></ul><h3><strong>Understanding the Maintenance Window in Android Doze Mode</strong></h3><p>When a phone enters Doze Mode, the operating system deliberately puts almost everything to sleep. However, to prevent apps from completely stopping, Android wakes the device up every few minutes for a very short period (a few seconds to a few tens of seconds). These short periods are called Maintenance Window. It manages by android power manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PovZeegVQEUzQ41BwiP9iw.png" /></figure><p>During this time, the system allows apps to:</p><ul><li>Run JobScheduler / WorkManager tasks</li><li>Perform sync operations</li><li>Send and receive network requests</li><li>Deliver normal FCM notifications</li><li>Execute alarms</li></ul><p>If you want to visualize it, the phone enters Doze</p><ul><li>Screen off</li><li>Phone stationary</li><li>CPU asleep</li><li>Network disconnected</li></ul><p><strong>After a few minutes, a “time box” opens</strong></p><ul><li>For a few seconds, the system allows:<br> ✔ CPU to wake up<br> ✔ Network to become active<br> ✔ Apps to perform pending tasks</li></ul><p><strong>The phone goes back to sleep</strong></p><ul><li>The next window is longer (the longer the phone stays in Doze, the farther apart the maintenance windows are, to save battery).</li></ul><pre>Device Idle           Doze Mode Active<br>|------Sleep------|Wake|----Sleep----|Wake|------Sleep------|Wake|<br>                  ↑                  ↑                    ↑<br>            Maintenance Window   Maintenance Window   Maintenance Window</pre><p>During Doze Mode, Android periodically wakes for a short maintenance window to allow apps to work.</p><pre>Time in Doze Mode →<br>Window Duration ↑<br><br>|         ■<br>|      ■<br>|   ■<br>| ■<br>+-----------------------<br>  Start   1hr   3hr   6hr</pre><p>Early windows may last 5–10 seconds, later could extend to<strong> </strong>minutes.</p><h3><strong>What Apps Can Do During Maintenance Window</strong></h3><p>When Android briefly wakes the device in Doze mode, apps are allowed to perform certain tasks during the short maintenance window:</p><p><strong>1.Run scheduled jobs</strong></p><ul><li>Jobs scheduled with JobScheduler or WorkManager<strong> c</strong>an execute.</li><li>Examples: background data processing, database cleanup, or deferred tasks.</li></ul><p><strong>2. Sync data</strong></p><ul><li>Apps can synchronize with their servers, like updating contacts, calendar events, or app-specific data.</li></ul><p><strong>3. Network communication</strong></p><ul><li>Apps can send or receive network requests (HTTP calls, API requests).</li><li>Normal FCM notifications (not high-priority ones) can be delivered.</li></ul><p><strong>4. Execute alarms</strong></p><p>Alarms set with AlarmManager can trigger during this period.</p><p><strong>Important:</strong></p><ul><li>This window is very short (a few seconds to tens of seconds).</li><li>Once the window ends, the device goes back to Doze and normal background operations are paused until the next window.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ri44NJ7SIKiS1hW1fIVWRA.png" /></figure><p>The maintenance window in Android Doze Mode is critical for balancing battery efficiency and app functionality. Developers must design apps to rely on scheduled background windows rather than constant background work.</p><p>This leads to:</p><ul><li>Better battery life</li><li>Smarter resource scheduling</li><li>More reliable background operations</li></ul><p>In the article <em>How Doze Mode Affects Location Providers</em>, we examined the <a href="https://medium.com/@mahbooberezaee68/how-doze-mode-affects-location-providers-392a499c03eb"><strong>impact of Android’s Doze Mode on the availability of location providers.</strong></a> If you’re interested in this topic, we also recommend reading this article.</p><p>This article has explored <strong>All You Need To Know About Doze Mode In Android Phones.</strong> I hope you’ve found it informative and engaging. If you enjoyed this content, feel free to show your support by clapping <strong>👏</strong>, following or leaving a comment below suggesting future topics you’d like to see covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e10f04bd7764" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Jetpack Compose?]]></title>
            <link>https://medium.com/@mahbooberezaee68/what-is-jetpack-compose-6fc0eb9f216a?source=rss-33aceb473967------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fc0eb9f216a</guid>
            <dc:creator><![CDATA[Bahar]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 18:28:39 GMT</pubDate>
            <atom:updated>2025-11-10T18:28:39.959Z</atom:updated>
            <content:encoded><![CDATA[<p>The name <strong>Jetpack Compose</strong> is a combination of two distinct, meaningful parts: <strong>Jetpack</strong> and <strong>Compose</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Inu-KAMvsobEfl4uS95dZw.png" /></figure><p><strong>Jetpack Compose</strong> is the official <strong>(Jetpack)</strong> tool for <strong>building the UI by combining small pieces (Compose)</strong>.</p><p>Here is the breakdown of why Google chose this specific name for its modern UI toolkit:</p><h4><strong>Jetpack</strong> (The Toolbox)</h4><p>The Jetpack portion of the name comes from Google’s extensive collection of modern libraries designed to streamline Android development. By packaging essential tools, Jetpack helps developers write better apps more quickly by managing challenging background processes such as lifecycle management and database operations. Therefore, calling it ‘Jetpack Compose’ confirms its status as an official, fundamental, and recommended tool within the current Android ecosystem.</p><h3>What does the word “Compose” mean?</h3><p>The word <strong>Compose</strong> simply means to put different things together to make one whole item. In programming, we compose the screen — we build the app’s look by combining small parts (or components).</p><h4>The Meaning of <strong>Composable</strong> in Jetpack Compose</h4><p>A Composable is any small piece of the UI that is capable of being built and combined on the screen. Simply put, anything that is displayed on your Android application screen — whether it’s a button, a piece of text, an image, or even a layout structure (like a column or a row) — is a Composable. At the code level, a Composable is actually a Function that must have the special marker <strong>@Composable</strong> placed above it.</p><pre>@Composable // This marker shows that this is a Composable<br>fun SimpleText(name: String) {<br>    Text(text = &quot;Hello $name&quot;) // This &#39;Text&#39; itself is also a built-in Composable<br>}</pre><h3>Why are they called Composables?</h3><ul><li>They are called this because they are capable of being composed (combined).</li><li>You can take several small composables (like Text and Button) and place them inside a larger Composable (like Column or Row) to build a more complex section of the user interface.</li></ul><p>So, compose is the verb describing the act of building a User Interface (UI) by combining various components. Conversely, Composable is the noun referring to those individual, small components (like a button, text, or image) that are designed to be combined.</p><p>In summary, <strong>Jetpack Compose</strong> is Google’s modern, official toolkit for <strong>building user interfaces by combining small, reusable components</strong>.</p><h3>Compose in Programming</h3><p>In <strong>Jetpack Compose</strong>, you build the app’s appearance by combining small pieces. For example, this code:</p><pre>@Composable<br>fun MyScreen() {<br>    Column(modifier= Modifier.fillMaxSize()) {<br>        Text(&quot;Hello Android&quot;)<br>        Button(onClick = { }) {<br>            Text(&quot;Click Me&quot;)<br>        }<br>    }<br>}</pre><p>Here, you are creating a screen using:</p><ul><li>A <strong>Text</strong> component.</li><li>A <strong>Button</strong> component.</li><li>A <strong>Column</strong> layout that places them vertically (one below the other).</li></ul><p>You have now <strong>composed</strong> a screen (i.e., you built it by combining components).</p><h3>The @Composable Signature</h3><p>In Compose, everything you see on the screen (a button, text, image) is built with a <strong>function</strong>. These are called <strong>Composable Functions</strong> and are marked with the @Composable annotation above them.</p><p>So, every Composable starts with the @Composable annotation:</p><pre>@Composable<br>fun MyScreen() {<br>    // ... inside here, you combine other Composables<br>}</pre><h3>Jetpack Compose vs. XML: The Core Difference</h3><p>Understanding the difference between Jetpack Compose and XML is exactly why Google created Compose.</p><h3>Old Way: XML (Separate Layout File)</h3><p>Imagine you want to show a text and a button.</p><p>In the old way (XML), you had to write the visual design in the activity_main.xml file:</p><pre>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:gravity=&quot;center&quot;<br>    android:padding=&quot;16dp&quot;&gt;<br>&lt;TextView<br>        android:id=&quot;@+id/helloText&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Hello World&quot;<br>        android:textSize=&quot;24sp&quot;<br>        android:textColor=&quot;#000000&quot;/&gt;<br>    &lt;Button<br>        android:id=&quot;@+id/clickButton&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Click Me&quot;/&gt;<br>&lt;/LinearLayout&gt;</pre><p>And <strong>then</strong>, you had to write code in MainActivity.kt to <strong>find</strong> and <strong>interact</strong> with these elements:</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContentView(R.layout.activity_main) // Load the XML file<br>    val helloText = findViewById&lt;TextView&gt;(R.id.helloText) // FIND the element<br>    val clickButton = findViewById&lt;Button&gt;(R.id.clickButton) // FIND the element<br>    clickButton.setOnClickListener {<br>        helloText.text = &quot;Button Clicked!&quot; // Manually change the UI<br>    }<br>}</pre><p>This required constant <strong>switching back and forth</strong> between the XML file (for appearance) and the Kotlin file (for logic).</p><h3>New Way: Jetpack Compose (Kotlin Only)</h3><p>You write the same thing with just a few lines of <strong>Kotlin</strong>:</p><pre>// Composable Function (Combines both appearance and logic)<br>@Composable<br>fun SimpleScreen() {<br>    Column(horizontalAlignment = Alignment.CenterHorizontally) {<br>        Text(&quot;Hello World&quot;, fontSize = 24.sp)<br>        Button(onClick = { <br>            // Logic goes right here!<br>            println(&quot;Button Clicked!&quot;) <br>        }) {<br>            Text(&quot;Click Me&quot;)<br>        }<br>    }<br>}</pre><p>And in MainActivity.kt, you just call your Composable to display it:</p><pre><br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent { // Tell Compose to display the content inside<br>            SimpleScreen() // Just call your Composable function<br>        }<br>    }<br>}</pre><p>That’s it!</p><ul><li>No findViewById.</li><li>No separate XML files.</li><li>No need to sync between different file types.</li></ul><p>This article has explored <strong>What is Jetpack Compose?</strong>. I hope you’ve found it informative and engaging. If you enjoyed this content, feel free to show your support by clapping <strong>👏</strong>, following or leaving a comment below suggesting future topics you’d like to see covered</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fc0eb9f216a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>