Skip to main content

32 posts tagged with "Bugs"

View All Tags

Why Flutter Deep Links Break in Release & How to Fix Them

Published: · 8 min read
Sandra Rosa Antony
Software Engineer, Appxiom

In local development, deep links feel deceptively simple. You run an adb command or test in an iOS simulator, and Flutter immediately opens /products/492.

Yet once the app ships to Google Play or the App Store, bug reports surface: links open the browser instead of the app, users land on an empty home screen, or iOS redirects to a web login.

When flutter deep linking release not working occurs in production, the root cause is rarely the Flutter framework itself. In development, local environments bypass the strict domain verification enforced by mobile operating systems. In production, keystore re-signing, Apple CDN caching, and native routing collisions cause links to fail silently.

Here is how to diagnose and resolve these failures across Android App Links, iOS Universal Links, and Flutter engine routing.

A deep link traverses three layers before rendering a Flutter screen:

Failures occur at two boundaries:

  1. OS Domain Verification Failure: Cryptographic checks fail against hosted domain manifests, prompting Android or iOS to abort app delegation and fall back to the browser.
  2. Native Route Interception Conflict: The OS opens the app, but Flutter’s native engine deep linking collides with application routers like go_router, dropping users onto fallback routes.

Android App Links require intent filters with android:autoVerify="true" and a verification file at https://yourdomain.com/.well-known/assetlinks.json. On Android 12+ (API 31+), failed verification silently opens Chrome without an app chooser.

The Trap: Google Play App Signing Keystore Mismatch​

The primary cause of flutter app links assetlinks json failure in release is a signature mismatch caused by Google Play App Signing.

When testing locally, developers extract the SHA-256 fingerprint from their local keystore:

keytool -list -v -keystore android/app/upload-keystore.jks -alias upload

Adding only this fingerprint to assetlinks.json works for local release builds. But when you upload an Android App Bundle (.aab), Google Play re-signs the app with Google's managed App Signing Key.

Users installing from Google Play receive an APK signed by Google's key. Android's IntentFilterVerificationReceiver detects an SHA-256 mismatch against assetlinks.json and rejects the domain.

The Correct assetlinks.json Configuration​

Your assetlinks.json must include fingerprints for both your local/upload keys and Google Play App Signing.

In the Google Play Console, go to Release > Setup > App integrity > App Signing > App signing key certificate. Copy the SHA-256 certificate fingerprint and update https://yourdomain.com/.well-known/assetlinks.json:

[
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.example.appxiomstore",
"sha256_cert_fingerprints": [
"F3:2B:64:18:...:AA:01",
"8A:E2:59:C1:...:9B:44"
]
}
}
]

Hosting Rules: Serve over HTTPS with valid SSL, return HTTP 200 OK with Content-Type: application/json, and avoid redirects (301/302).

Diagnosing Android Verification via adb​

Inspect verification state directly on a connected release device:

# Check domain verification status (Android 12+)
adb shell pm get-app-links com.example.appxiomstore

# Force re-verification without reinstalling
adb shell pm verify-app-links --re-verify com.example.appxiomstore

# Stream verification logs
adb logcat -s IntentFilterVerificationReceiver domain_verification

Verify endpoint accessibility using Google's Digital Asset Links API:

curl "https://digitalassetlinks.googleapis.com/v1/statements:list?source.web.site=https://yourdomain.com&relation=delegate_permission/common.handle_all_urls"

On iOS, Universal Links associate your Apple Team ID and Bundle ID with your web domain via the Apple App Site Association (apple-app-site-association or AASA) file.

When debugging universal links aasa flutter configurations, check these failure points:

In Xcode, under Signing & Capabilities > Associated Domains, domains require the applinks: scheme:

  • ❌ https://yourdomain.com
  • ✅ applinks:yourdomain.com

Without applinks:, Xcode builds successfully, but iOS ignores domain association.

2. HTTP Redirects and MIME Types​

Apple's scraper queries https://yourdomain.com/.well-known/apple-app-site-association. If the server returns a redirect (301/302), Apple's bot discards the file.

  • Return direct HTTP 200 OK.
  • Serve with Content-Type: application/json.
  • Do not append a .json file extension.

3. Apple CDN Proxy Caching​

Since iOS 14, devices fetch AASA manifests from Apple's CDN proxy (app-site-association.cdn-apple.com). Updates can take 24 to 48 hours to propagate.

Bypass the CDN during staging via developer mode in your entitlement:

<key>com.apple.developer.associated-domains</key>
<array>
<string>applinks:yourdomain.com?mode=developer</string>
</array>

(Remove ?mode=developer before production App Store submission).

4. Modern AASA Format​

Ensure the manifest uses the modern components schema with your exact <TeamID>.<BundleID>:

{
"applinks": {
"apps": [],
"details": [
{
"appIDs": [ "ABCDE12345.com.example.appxiomstore" ],
"components": [
{
"/": "/products/*",
"comment": "Product detail routes"
}
]
}
]
}
}

Engine Routing Conflicts: Resolving flutter_deeplinking_enabled​

Once domain verification passes, the OS hands the URL to the native runner (FlutterActivity on Android, FlutterAppDelegate on iOS).

Here, projects frequently hit a flutter_deeplinking_enabled conflict.

The Collision Mechanism​

By default, Flutter's native engine captures inbound deep links and dispatches them across SystemChannels.navigation.

If your app uses declarative routing (go_router) or link stream packages (app_links), both systems handle the event at once:

  1. Flutter's native engine pushes the raw URI directly to Navigator.
  2. GoRouter or app_links parses the URI to run route guards, query parameters, or authentication hydration.

This race condition causes classic release bugs:

  • Query parameters stripped: The engine routes /products?id=12 against /products, dropping query strings and landing on fallback screens.
  • Premature navigation before auth: The engine forces navigation before authentication states or token caches finish loading, bouncing users to /login.
  • Duplicate transitions: The destination screen animates twice or triggers navigation stack conflicts.

When to Disable Flutter's Built-in Deep Linking​

If you manage deep-link streams manually using app_links or custom platform channels, disable Flutter's default engine routing.

In android/app/src/main/AndroidManifest.xml:

<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:exported="true">

<meta-data
android:name="flutter_deeplinking_enabled"
android:value="false" />

<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="yourdomain.com" />
</intent-filter>
</activity>

In ios/Runner/Info.plist:

<key>FlutterDeepLinkingEnabled</key>
<false/>

Resilient Declarative Routing with GoRouter​

When using GoRouter without secondary link listeners, keep flutter_deeplinking_enabled active, but provide explicit error boundaries:

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

final GoRouter appRouter = GoRouter(
initialLocation: '/',
errorBuilder: (context, state) => Scaffold(
body: Center(
child: Text('Unable to load: ${state.uri.path}'),
),
),
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/products/:id',
builder: (context, state) => ProductDetailScreen(
productId: state.pathParameters['id'] ?? '',
promoCode: state.uri.queryParameters['promo'],
),
),
],
);

Measuring Goal Friction Impact (GFI) with Appxiom​

When a deep link fails in release, traditional APM tools report zero crashes and a 99.9% crash-free session rate. The app simply booted to / or remained in the browser.

However, if marketing spent an illustrative $50,000 on a campaign and high-intent users land on an empty home screen or an unhandled 404, those users abandon immediately.

This is the blind spot Appxiom's Goal Friction Impact (GFI) measures:

  1. User Journey Attribution: Appxiom monitors deep-link entry points to detect native route failures, broken fallbacks, and routing friction before users abandon critical paths.
  2. Detecting Silent Fallbacks: When users enter via a deep link but stall on fallback screens or bounce within seconds, Appxiom flags the friction event.
  3. Quantifying Revenue Loss: GFI calculates the financial impact of broken routes, turning a vague bug report into actionable data - such as identifying a missing Google Play fingerprint that resulted in an illustrative $24,000 in lost revenue.

Troubleshooting Reference​

IssueRoot CauseFix
Android: Link opens Chrome directlyKeystore mismatch in assetlinks.json.Add Google Play App Signing SHA-256 to assetlinks.json.
Android: Verification stuck in legacy_failureHTTP redirect or invalid SSL on assetlinks.json.Serve direct 200 OK via HTTPS with application/json.
iOS: Universal Link opens SafariMissing applinks: prefix in Xcode capabilities.Use applinks:yourdomain.com in Associated Domains.
iOS: AASA changes not taking effectApple CDN proxy caching (up to 48 hours).Add ?mode=developer to entitlement during testing.
Flutter: App opens to blank screen or 404Collision between native link handling and package router.Set flutter_deeplinking_enabled to false when managing streams via app_links.

Best Practices​

  1. Include Both Key Fingerprints: Keep both upload and Play App Signing SHA-256 fingerprints in assetlinks.json.
  2. Eliminate Manifest Redirects: Ensure CDN rules serve assetlinks.json and apple-app-site-association directly without redirects.
  3. Provide Fallback Route Handlers: Configure resilient errorBuilder pages in GoRouter to prevent white screens when deep links fail.
  4. Track Funnel Drop-offs: Use Appxiom GFI to monitor deep-link conversion funnels on every release track.

Conclusion​

Release deep-linking failures stem from configuration mismatches across operating system domain verification, CDN caching, and Flutter's native routing layer.

By aligning your Google Play App Signing keys, configuring zero-redirect AASA endpoints, resolving engine routing conflicts with flutter_deeplinking_enabled, and monitoring Goal Friction Impact with Appxiom, you can ensure users transition smoothly into your app on every release.

Production Memory Diagnostics: Tracking Leaks, OOMs, and Jetsam in Mobile Apps

Published: · 13 min read
Robin Alex Panicker
Cofounder and CPO, Appxiom

In local development, diagnosing a memory leak is a solved problem.

You fire up Android Studio Memory Profiler or Xcode Instruments Allocations, attach a debugger, record a trace, inspect the object graph, or let LeakCanary dump a heap snapshot. Within minutes, you can pinpoint the exact retain cycle or static reference pinning an Activity or UIViewController in RAM.

In production, that luxury vanishes.

Running a heap dump in a live production app is an engineering non-starter. A standard Android heap dump (Debug.dumpHprofData()) freezes the main thread for 10 to 30 seconds, creates an uncompressed 500MB+ .hprof file on user storage, risks exfiltrating unredacted Personally Identifiable Information (PII), and frequently triggers operating system watchdogs. On iOS, you cannot capture memory graphs or attach Instruments to App Store binaries at all.

Even worse, Out-Of-Memory (OOM) events are the most silent killers in mobile engineering.

When an iOS device runs out of physical RAM, Apple's Jetsam kernel daemon terminates your process with a SIGKILL. On Android, the LowMemoryKiller daemon (lmkd) sends a silent kill to reclaim pages.

Neither operating system gives your application time to execute an uncaught exception handler. Traditional crash reporting SDKs register zero crash logs. To your backend and analytics dashboards, the user simply disappeared - or worse, the app restarts cleanly on next launch, disguising catastrophic memory exhaustion as ordinary user session churn.

Here is how modern engineering teams move beyond development-only profilers to implement Production Memory Diagnostics - tracking runaway allocations, memory leaks, and OS termination events without degrading app performance.

Production Memory Diagnostics is the practice of continuously monitoring runtime memory health (Resident Set Size, dirty physical footprint, system memory pressure warnings, and screen-by-screen memory deltas) on live user devices without capturing heavy heap dumps. By correlating memory growth with user journeys and lifecycle events, production diagnostics identify retain cycles, native cache bloat, and LowMemoryKiller (LMK)/Jetsam terminations before they cause silent churn.

The Anatomy of Silent Memory Kills​

To diagnose production memory issues, you must first understand how modern mobile operating systems enforce memory limits and terminate processes.

1. iOS: The Jetsam Mechanism (FOOM)​

iOS devices operate without a traditional disk swap file. To manage memory pressure, iOS relies on memory compression and aggressive process termination enforced by the kernel daemon memorystatus (commonly known as Jetsam).

When an app's dirty physical memory footprint crosses the system limit (which varies by device model and memory tier - often between 1.2GB and 2.2GB on modern iPhones, but as low as 350MB on older iPads or memory-constrained extensions), Jetsam sends an uncatchable SIGKILL.

The Virtual Memory Trap​

Many developers attempt to track memory in Swift by reading task_basic_info.virtual_size. This metric is virtually useless: virtual size includes clean mapped read-only files (such as .dylib frameworks and asset catalogs) that the OS can evict at zero cost.

Jetsam only cares about Physical Footprint - dirty pages that cannot be compressed or paged out.

Low-Overhead Physical Footprint Telemetry in Swift​

To capture actual memory pressure in production, you must query the Mach kernel's task_vm_info:

import Foundation
import MachO

public struct MemoryDiagnostics {

/// Returns the exact physical memory footprint (in Megabytes) tracked by Jetsam.
public static func getPhysicalMemoryFootprintMB() -> Double? {
var vmInfo = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)

let result = withUnsafeMutablePointer(to: &vmInfo) { ptr in
ptr.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { intPtr in
task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), intPtr, &count)
}
}

guard result == KERN_SUCCESS else { return nil }

// phys_footprint is the exact metric used by iOS Jetsam to trigger kills
let footprintBytes = Double(vmInfo.phys_footprint)
return footprintBytes / (1024.0 * 1024.0)
}

/// Queries remaining memory available to the process before system intervention
public static func getAvailableMemoryMB() -> Double {
return Double(os_proc_available_memory()) / (1024.0 * 1024.0)
}
}

By querying os_proc_available_memory() upon entering critical funnels, your app can dynamically evict caches before Jetsam strikes.

2. Android: The LowMemoryKiller (LMK) & The OOM Paradox​

On Android, memory management is split across two layers:

  1. The ART (Android Runtime) Java/Kotlin Virtual Heap: Subject to garbage collection with an upper limit defined by Runtime.getRuntime().maxMemory().
  2. The Linux Kernel & Native Allocations: Governed by the lmkd daemon, which monitors system-wide RAM and kills processes based on their oom_score_adj priority.

The "Straw That Broke the Camel's Back" Fallacy​

When an Android app crashes with a fatal java.lang.OutOfMemoryError, developers almost always misdiagnose the root cause by staring at the stack trace:

java.lang.OutOfMemoryError: Failed to allocate a 32784 byte allocation with 12582912 free bytes and 12MB until OOM
at java.lang.StringFactory.newStringFromChars(StringFactory.java:328)
at java.lang.StringBuilder.toString(StringBuilder.java:407)
at com.example.app.ui.cart.CartAdapter.onBindViewHolder(CartAdapter.kt:42)

The stack trace points to a 32KB string allocation inside CartAdapter. Developers spend days optimizing StringBuilder usages in the cart screen.

In reality, the cart adapter was blameless. Five minutes earlier, a background image pipeline leaked five 50MB uncompressed Bitmap instances because an Activity failed to unsubscribe from an EventBus. The heap was already at 99.8% capacity; the 32KB string just happened to be the unlucky allocation that tripped the wire.

Production Memory Telemetry in Kotlin​

To monitor real memory consumption and intercept OS warnings before LMK strikes:

package com.appxiom.diagnostics

import android.app.ActivityManager
import android.content.ComponentCallbacks2
import android.content.Context
import android.content.res.Configuration
import android.os.Debug
import android.os.Process

class ProductionMemoryObserver(private val context: Context) : ComponentCallbacks2 {

fun captureMemorySnapshot(): MemorySnapshot {
val runtime = Runtime.getRuntime()
val javaHeapUsedMB = (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024)
val javaHeapMaxMB = runtime.maxMemory() / (1024 * 1024)

// Native allocation tracking (Bitmaps, C++ libs, OpenGL/Vulkan buffers)
val nativeHeapAllocatedMB = Debug.getNativeHeapAllocatedSize() / (1024 * 1024)

// PSS (Proportional Set Size): The most accurate representation of app footprint
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val memoryInfo = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(memoryInfo)

return MemorySnapshot(
javaHeapUsedMB = javaHeapUsedMB,
javaHeapMaxMB = javaHeapMaxMB,
nativeHeapAllocatedMB = nativeHeapAllocatedMB,
systemAvailableMemMB = memoryInfo.availMem / (1024 * 1024),
isSystemLowMemory = memoryInfo.lowMemory
)
}

override fun onTrimMemory(level: Int) {
when (level) {
ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL -> {
// The app is running, but device is critically low on memory.
// Evict non-essential bitmap caches immediately.
}
ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN -> {
// UI moved to background. Free heavy UI resources to lower LMK kill priority.
}
}
}

override fun onConfigurationChanged(newConfig: Configuration) {}
override fun onLowMemory() {
// Legacy callback: system is running out of memory
}
}

data class MemorySnapshot(
val javaHeapUsedMB: Long,
val javaHeapMaxMB: Long,
val nativeHeapAllocatedMB: Long,
val systemAvailableMemMB: Long,
val isSystemLowMemory: Boolean
)

3. Flutter & React Native: The Split-Heap Blindspot​

Cross-platform frameworks introduce a dangerous architectural duality: The VM Heap vs. The Native Graphics Engine.

In Flutter, Dart manages object lifecycle on the Dart VM Heap. However, images, shaders, Skia/Impeller render pipelines, and texture backings live in native C++ memory.

// DANGEROUS: Decodes a 4032x3024 12MB camera photo into raw RGBA memory
// Dart heap allocates only a tiny metadata pointer (~120 bytes)
// Skia / Native heap allocates 4032 * 3024 * 4 bytes = ~48.7 MB of uncompressed bitmap!
Image.network(
"https://cdn.example.com/products/4k_photo.jpg",
width: 150,
height: 150,
)

// SAFE: Resizes bitmap during decode step, saving 95% native RAM
Image.network(
"https://cdn.example.com/products/4k_photo.jpg",
width: 150,
height: 150,
cacheWidth: 300, // 2x density for 150dp
cacheHeight: 300,
)

If a list view displays 30 unconstrained images, the Dart VM reports a healthy 45MB heap, while the native iOS/Android process footprint spikes past 1.4GB. Within seconds, Jetsam or LMK kills the app. A standard Dart crash handler will never capture a stack trace.

Why Traditional Monitoring Tools Fail in Production​

CapabilityLocal Dev Profilers (Xcode / Android Studio)LeakCanaryStandard Crash Reporters (Crashlytics, Sentry)Production Memory Diagnostics (Appxiom)
Run in Production App Store / Play Store❌ No (Debug builds only)❌ Dangerous (5-30s freeze, PII risk)✅ Yes✅ Yes
Zero UI Jitter / Overhead❌ High overhead❌ High pause time✅ Low✅ Zero-overhead passive telemetry
Capture Jetsam / FOOM Kills❌ N/A❌ N/A❌ Misses SIGKILL terminations✅ Correlates last known footprint
Capture Native vs Managed Heap✅ Yes❌ Java heap only❌ None✅ Complete physical footprint
Attribution to User Action⚠️ Manual profiling session❌ Static reference path only❌ Single stack frame at crash✅ Full historical Activity Trail

The Appxiom Solution: Memory Activity Trail​

Diagnosing production memory leaks does not require capturing every allocated byte in RAM. It requires understanding Memory Delta Attribution.

A leak is not defined by high memory usage; it is defined by memory that is allocated during a user journey and fails to reclaim after that journey terminates.

Correlating Memory Deltas with User Journeys​

The Appxiom SDK records lightweight memory snapshots attached to each discrete step in the Activity Trail. By comparing memory footprint across screen transitions, network invocations, and user interactions, Appxiom calculates the exact memory delta ($\Delta$) per step.

Activity Trail Trace: Diagnosing a Retain Cycle in Production​

Consider this telemetry log captured by Appxiom immediately before an iOS Jetsam event:

TimestampScreen / Lifecycle EventAction / PayloadPhysical RAMMemory Delta ($\Delta$)Status
14:22:01.100AppLaunchCold start from springboard98 MB+98 MBNormal
14:22:04.250HomeScreenFeed fetch (GET /v2/feed - 200)132 MB+34 MBNormal
14:22:15.800CatalogScreenGrid populated (48 products)168 MB+36 MBNormal
14:22:28.400ARProductViewerCamera initialized + 3D model load495 MB+327 MBHigh Allocation
14:22:42.100HomeScreenUser navigates BACK to Home490 MB-5 MB (LEAK ALERT)CRITICAL
14:22:49.000CartScreenUser taps Cart icon510 MB+20 MBWarning
14:22:53.600CheckoutScreenTap "Pay Now"542 MB+32 MBJETSAM KILL

The Root Cause Revealed​

Without Appxiom, your team would be looking at an unhandled session termination during checkout. You might assume the payment gateway SDK crashed.

With the Appxiom Activity Trail, the bug is obvious in five seconds:

  1. When the user entered ARProductViewer, RAM jumped from 168 MB to 495 MB (+327 MB).
  2. When the user navigated back to HomeScreen, memory should have dropped back toward 168 MB. Instead, memory remained pinned at 490 MB (only -5 MB reclaimed).
  3. The ARProductViewer controller or its Metal texture buffers had a strong retain cycle (e.g., an uncancelled closure capture or unreleased camera delegate), keeping 320MB of native resources permanently alive in background memory.
  4. When the user reached Checkout, the normal memory requirement of the payment sheet pushed the app over the device's Jetsam threshold.

Connecting Memory Diagnostics to Business Health​

Memory diagnostics is not merely an infrastructure concern; it directly impacts revenue and customer retention.

1. Goal Friction Impact (GFI)​

When an app terminates due to an OOM during an onboarding or checkout flow, users rarely re-enter payment credentials - they abandon the transaction. Appxiom's Goal Friction Impact (GFI) quantifies the precise financial loss attributable to memory degradation, allowing engineering leads to prioritize memory fixes with hard ROI data.

2. Quality Score (QS)​

Rather than relying solely on the deceptive crash-free rate, Appxiom calculates a holistic Quality Score (QS). Devices experiencing excessive memory pressure warnings (TRIM_MEMORY_RUNNING_CRITICAL or didReceiveMemoryWarningNotification) trigger a score penalty, giving you an early warning system days before crashes escalate.

3. Version Analytics​

During staged rollouts, Appxiom's Version Analytics compares memory distributions across app versions:

  • v2.4.0: 90th percentile physical footprint = 185 MB.
  • v2.5.0: 90th percentile physical footprint = 340 MB (+83% regression detected in first 2% rollout).

You can halt the release before the regression compromises millions of devices.

Actionable Production Memory Hardening Checklist​

Follow these engineering best practices to eliminate memory leaks and build resilience against LMK and Jetsam:

iOS (Swift / SwiftUI)​

  • Enforce Weak Capture in Async Closures: Audit all Task { [weak self] in ... } blocks and delegates to prevent retain cycles holding view controllers in memory.
  • Drain Autorelease Pools in Heavy Loops: Wrap batch data transforms or file processing in autoreleasepool { ... } so intermediate objects are reclaimed immediately.
  • Listen to Memory Pressure: Implement UIApplication.didReceiveMemoryWarningNotification to flush image memory caches and clear transient view states.
  • Audit Background Tasks: Ensure background tasks end promptly with UIApplication.shared.endBackgroundTask(). Pinned background allocations are the #1 trigger for Jetsam priority kills.

Android (Kotlin / Jetpack Compose)​

  • Observe ComponentCallbacks2: Evict Glide/Coil bitmap caches upon receiving TRIM_MEMORY_RUNNING_CRITICAL or TRIM_MEMORY_RUNNING_LOW.
  • Beware of Static View/Context References: Never store a Context or View in a companion object, singleton, or long-lived coroutine scope.
  • Bind Coroutines to Lifecycle: Use viewLifecycleOwner.lifecycleScope in Fragments and rememberCoroutineScope() in Compose to ensure allocations cancel with UI teardown.
  • Optimize Large Bitmaps: Always decode images using BitmapFactory.Options.inSampleSize or rely on modern vector drawables and hardware-accelerated rendering.

Cross-Platform (Flutter / React Native)​

  • Constrain Image Cache Dimensions: Never use unconstrained Image.network() without specifying cacheWidth and cacheHeight.
  • Dispose Controllers Explicitly: Always invoke .dispose() on AnimationController, TextEditingController, FocusNode, and ScrollController in the widget dispose() lifecycle.
  • Verify Native Bridge Cleanup: Ensure custom native platform channels (MethodChannels) release native listeners and texture handles when widgets unmount.

Eliminate Memory Blindspots with Appxiom​

You cannot fix what you cannot measure, and you cannot debug production memory with development-only profilers.

By combining low-overhead physical footprint telemetry with the Appxiom Activity Trail, your engineering team gains complete visibility into every memory spike, retain cycle, and silent OOM kill across iOS, Android, and Flutter.

Stop losing users to invisible memory kills. Explore Appxiom's Activity Trail or start monitoring your mobile applications today.

Silent Failures, ANRs, and App Hangs: How to Detect and Fix the Bugs That Never Crash

Published: · 15 min read
Don Peter
Cofounder and CTO, Appxiom

Your crash reporting dashboard displays a pristine 99.9% crash-free session rate.

Your engineering team celebrates a successful deployment. The release metrics look flawless. But on the App Store and Google Play, your reviews tell a completely different story:

"The app freezes every time I tap the checkout button. Completely unusable."
"It just spins forever on the login screen. Had to force close and uninstall."
"Buttons become unresponsive after opening my transaction history."

Meanwhile, your product manager pulls up analytics: checkout funnel completion has plummeted by 22%, and customer churn is spiking. Yet your error monitor reports zero fatal crashes.

How can an application be catastrophic for users while registering as 100% healthy on your APM dashboard?

Welcome to the blind spot of modern software monitoring: Silent Failures, Application Not Responding (ANR) events, and iOS App Hangs.

The Dangerous Illusion of the Crash-Free Rate​

For more than a decade, mobile engineering teams have used Crash-Free Session Rate (CFSR) as their primary release quality benchmark.

The flaw with CFSR is structural: it measures process survivability, not user experience.

When a mobile app freezes, the process is still running. When an API call fails and leaves a progress indicator spinning indefinitely, no unhandled exception is thrown. When a user force-closes the app in frustration, the operating system registers a user termination, not a crash.

To your crash logger, that session was a victory. To your user, it was an infuriating failure.

Deconstructing the Three Horsemen of Silent Decay​

To eliminate silent failures, engineering teams must understand the three distinct technical mechanisms that cause them:

1. Android ANRs (Application Not Responding)​

On Android, the operating system monitors UI responsiveness via the system server. If your application cannot process input events or lifecycle callbacks within designated timeframes, Android displays the dreaded Application Not Responding (ANR) dialog:

app is not responding

Close app
Wait

What Triggers an ANR?​

  • Input Dispatching Timeout: The app fails to respond to an input event (e.g., key press or screen touch) within 5 seconds.
  • BroadcastReceiver Timeout: A BroadcastReceiver fails to finish executing within 10 seconds in foreground mode.
  • Service Execution Timeout: A Service executed by the foreground app fails to complete its lifecycle tasks within 20 seconds.

The Business Penalty: Google Play Vitals​

Google Play monitors your app's User-Perceived ANR Rate (ANRs occurring when your app is in the foreground). If your ANR rate exceeds Google's bad behavior threshold of 0.47% overall (or 8% on specific phone models):

  • Google demotes your app in Play Store search rankings.
  • Your app is disqualified from store featuring and promotional carousels.
  • Google Play displays a warning directly on your store listing: "Recent data shows that this app may stop working on your device."

2. iOS App Hangs​

iOS does not display an ANR dialog. Instead, when the main run loop is blocked, the interface simply stops accepting touch input. Tapping buttons produces no ripple effect, scrolling locks up, and animations stutter to a halt.

What Triggers an App Hang?​

The iOS main thread operates as an event run loop (CFRunLoop). When an operation performs synchronous disk I/O, heavy computation, or waits on a dispatch semaphore on the main thread, the run loop cannot process new touch events.

  • Micro-Hangs (250ms – 500ms): Perceived by users as "jank," dropped frames, or sluggishness.
  • Severe Hangs (> 2,000ms): Users perceive the app as completely frozen. Over 70% of users will force-quit an app if an interaction takes longer than 3 seconds without visual feedback.

Apple Xcode Organizer Telemetry​

Apple tracks your Hang Rate (measured as milliseconds of hang time per hour of active use). High hang rates directly suppress your visibility in App Store search results and elevate user churn.

3. Silent Functional Failures & Swallowed Exceptions​

Unlike ANRs and App Hangs, silent functional failures often involve zero thread contention. Instead, they are caused by defensive programming gone wrong:

// The Classic "Silent Killer" Pattern:
try {
val response = paymentApi.confirmPurchase(orderId)
updateUiWithReceipt(response)
} catch (e: Exception) {
// Exception caught and logged to console or an unmonitored analytics tag
Log.e("Payment", "Purchase failed", e)
// The spinner continues to animate, or the screen never transitions!
}

The network request times out, or the backend returns a 503 Service Unavailable. Because the exception was caught, no crash occurred. But the user is left looking at an unresponsive checkout button. They tap it three more times, get no feedback, and leave your app forever.

Why Traditional APMs Fail to Diagnose ANRs and Hangs​

Most engineering teams rely on crash loggers to debug ANRs. When an ANR occurs, these tools capture a point-in-time thread dump. But in production, these thread dumps are notoriously misleading:

1. The "Innocent Bystander" Stack Trace​

When an operating system triggers an ANR dump at second 5, the thread dump records whatever code happens to be executing at that exact millisecond. Frequently, this is an innocent operating system wait call:

"main" prio=5 tid=1 Native
#00 pc 000000000004b344 /apex/com.android.runtime/lib64/bionic/libc.so (syscall+28)
#01 pc 00000000001ae4f8 /apex/com.android.art/lib64/libart.so (art::ConditionVariable::WaitHoldingLocks)

The stack trace tells you the main thread is waiting for a lock. But which thread holds the lock? And what action caused the lock to be acquired in the first place? The thread dump cannot answer either question.

2. Lack of Preceding User Interaction Context​

Did the user tap a filter button? Did they background the app and return? Did their network connection drop from Wi-Fi to cellular right before the freeze? Standard thread dumps provide zero historical sequence.

3. No Correlation to Business Impact​

If an ANR occurs during app startup on an obsolete Android 8 device, it is an annoyance. If an App Hang occurs every time a high-value customer taps "Complete Purchase" on iOS 18, it is a business catastrophe. Traditional tools treat both events as isolated technical entries.

How Appxiom Solves Silent Failures: Continuous Forensics​

Appxiom tackles silent failures by bridging the gap between technical thread execution and user experience:

1. Proactive Main-Thread Watchdogs​

Appxiom continuously monitors UI thread responsiveness and runloop latency. If a task stalls the UI thread for longer than your defined threshold, Appxiom captures the event before the user force-closes the application.

2. The Activity Trail: Reconstructing the Crime Scene​

Instead of an isolated thread dump, Appxiom attaches the complete Activity Trail to every ANR and App Hang report:

APPXIOM ANR REPORT

Issue: ANR Detected (Main thread blocked for 5,240ms)
Version: v3.4.1 (Build 92)  |  Device: Samsung Galaxy S23  |  OS: Android 14

TIME

TYPE

DETAILS

FREE MEM

14:10:02.115LIFECYCLEOrdersActivity:onResume52.1%
14:10:03.450USER ACTIONClicked "Sync Offline Orders"51.8%
14:10:03.480CUSTOMlocal_db_query_started51.8%
14:10:03.490HTTPPOST /api/v2/orders/sync → 200 OK (310ms)51.2%
14:10:03.810CUSTOMparsing_5000_json_items49.5%
14:10:08.730ISSUE

ANR: Main thread stalled during JSON parsing for 5,240ms

48.9%

What this tells the engineer:​

In 15 seconds, the developer sees what happened:

  1. The user tapped 'Sync Offline Orders'.
  2. The network request succeeded quickly (200 OK in 310ms).
  3. The response contained 5,000 JSON items.
  4. The JSON parsing and database insertion were executed synchronously on the main thread instead of offloaded to a background coroutine or thread pool.
  5. The UI froze for 5.2 seconds, triggering the ANR.

3. Goal Friction Impact (GFI)​

Through Goal Friction Impact, Appxiom correlates silent ANRs and hangs directly to user drop-offs in critical funnels (such as checkout, signup, or subscription).

If a silent freeze occurs in a settings menu, its GFI score is low (e.g., 1.2/10). If an App Hang occurs during credit card validation, its GFI spikes to 9.6/10, immediately alerting your team to a revenue-critical blocker.

4. Appxiom Quality Score (QS)​

Unlike binary crash-free rates, the Appxiom Quality Score evaluates version health on a unified 0–10 scale that penalizes ANRs, App Hangs, and slow screen loads alongside fatal crashes.

Technical Best Practices: Preventing Main-Thread Freezes​

Eliminating ANRs and App Hangs requires architectural discipline across your codebase. Here are the core patterns to enforce:

Android: Moving Work Off the Main Thread​

1. Enforce Background Dispatchers for I/O​

Never perform disk reads, SharedPreferences writes, Room queries, or network operations on Dispatchers.Main:

// BAD: Runs on Main Thread, causes ANR under heavy DB load
fun loadUserTransactions() {
val transactions = database.transactionDao().getAll() // BLOCKS UI THREAD
updateUi(transactions)
}

// GOOD: Offloaded to Dispatchers.IO with Kotlin Coroutines
fun loadUserTransactions() = viewModelScope.launch {
val transactions = withContext(Dispatchers.IO) {
database.transactionDao().getAll()
}
updateUi(transactions)
}

2. Enable StrictMode in Debug Builds​

Catch disk and network violations during development before they ever reach production:

if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build()
)
}

iOS: Eliminating Runloop Blocking in Swift​

1. Leverage Swift 6 Concurrency & Actor Isolation​

Ensure heavy computations are decoupled from the @MainActor:

// BAD: Synchronous heavy parsing on the main actor
@MainActor
func processOrderHistory(data: Data) {
let decoder = JSONDecoder()
// Heavy JSON parsing locks the main runloop
let orders = try? decoder.decode([Order].self, from: data)
self.displayOrders(orders)
}

// GOOD: Background task processing
@MainActor
func processOrderHistory(data: Data) async {
let orders = await Task.detached(priority: .userInitiated) {
let decoder = JSONDecoder()
return try? decoder.decode([Order].self, from: data)
}.value

self.displayOrders(orders)
}

2. Avoid Synchronous Semaphore Waits on the Main Queue​

Never call dispatch_semaphore_wait or DispatchGroup.wait() on the main thread while waiting for a background completion handler. If the background thread requires main-thread access to complete, your app enters an immediate deadlock.

Flutter: Isolates for Heavy Computation​

In Flutter, the Dart engine runs on a single event loop. If you perform heavy operations on that loop, you freeze the UI across both Android and iOS simultaneously:

// BAD: Blocks Flutter root isolate
void parseLargeJson(String rawJson) {
final data = jsonDecode(rawJson); // Drops frames or triggers ANR
setState(() => items = data);
}

// GOOD: Offload to background Isolate using compute()
Future<void> parseLargeJson(String rawJson) async {
final data = await compute(jsonDecode, rawJson);
setState(() => items = data);
}

Comparison: Fatal Crash Monitoring vs. Appxiom Observability​

CapabilityTraditional Crash Loggers (Crashlytics, Bugsnag)Appxiom Performance & Error Platform
Fatal Exception Tracking✅ Yes✅ Yes
Android ANR Detection⚠️ Post-mortem thread dumps only✅ Real-time watchdog + Activity Trail
iOS App Hang Detection❌ Limited or omitted✅ Micro-hang & severe hang tracking
Silent API & State Failures❌ Omitted (process stays alive)✅ Automatic 4xx/5xx & flow block detection
User Interaction Footsteps❌ Generic breadcrumbs✅ Auto-tracked taps, gestures & lifecycles
Business Impact Metric❌ Occurrence count only✅ Goal Friction Impact (0–10 GFI Score)
Holistic Version Quality❌ Binary Crash-Free Rate✅ Appxiom Quality Score (0–10 QS)

The End of Invisible Bugs​

A crash that affects 10 users in an obscure background service is easy to spot on your dashboard.

An App Hang that freezes 5,000 customers during checkout is far more devastating—yet traditional monitoring platforms let it slip by in complete silence.

Stop relying on vanity metrics that disguise broken user experiences as healthy releases.

With Appxiom, you detect the failures that matter most:

  • Pinpoint the exact line of code causing your ANRs and App Hangs.
  • Retrace the user footsteps that led to the freeze.
  • Protect your App Store rankings and Google Play Vitals.
  • Fix release regressions before they cost you revenue.

Stop Letting Silent Failures Drain Your Revenue​

See how Appxiom gives mobile engineering teams the clarity they need to eliminate ANRs, App Hangs, and invisible regressions.

Start Your Free Appxiom Trial Today or explore our types of bugs detected in mobile and web apps.

Stop Guessing 'How to Reproduce': Debugging Release Regressions with Appxiom's Activity Trail

Published: · 17 min read
Andrea Sunny
Marketing Associate, Appxiom

You just shipped version v4.2.0 of your mobile application. Every unit test passed in CI, staging looked rock-solid, and the release train left the station on schedule.

Twenty-four hours later, the Slack notifications start pouring in.

Customer support is escalating tickets. App Store reviews are dropping from 4.8 to 3.2 stars. Product managers are asking why checkout conversion dropped by 18%. And on Jira, you are assigned a ticket titled:

"App crashes or freezes when user tries to place an order after applying coupon."
Steps to Reproduce: "Unknown. Just tap around in the cart."

You pull up your error tracker - Firebase Crashlytics, Sentry, or Bugsnag. You find the stack trace:

Fatal Exception: java.lang.IllegalStateException: 
Can not perform this action after onSaveInstanceState
at androidx.fragment.app.FragmentManager.checkStateLoss(FragmentManager.java:1844)
at androidx.fragment.app.FragmentManager.enqueueAction(FragmentManager.java:1884)
at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:329)
at com.example.store.checkout.CheckoutFragment.showOrderConfirmation(CheckoutFragment.kt:342)

You open the codebase. You launch the emulator on your workstation. You add an item to the cart, apply a coupon, tap checkout, and... it works completely fine.

You test it on five different test devices. It works fine on every single one.

You reply to the ticket: "Unable to reproduce locally. Need more info." QA replies: "We saw it twice on staging, but can't replicate it consistently." Support asks the customer for a screen recording. The customer ignores the email and uninstalls the app.

Welcome to the most demoralizing, soul-crushing ritual in modern software engineering: debugging production release regressions without knowing what the user actually did.

Why Stack Traces Fail: The Point-of-Impact Fallacy in Production Regressions​

For the past fifteen years, engineering teams have relied on stack traces as the primary source of truth for software defects. But mobile applications have evolved into complex, asynchronous, multi-threaded state machines.

When an issue occurs in production, a stack trace only tells you where the process failed (the point of impact). It tells you virtually nothing about the sequence of events that created the corrupted state (the crime scene).

Traditional Crash ReportingVisibility / Details
Point-of-Impact Stack TraceLine 342 in CheckoutFragment
"What broke?"IllegalStateException
"What was the user doing 5 seconds before?"❓ Unknown
"Which buttons were tapped?"❓ Unknown
"Did the network drop or switch?"❓ Unknown
"Was the app backgrounded and restored?"❓ Unknown

Consider the typical root causes of production release regressions that make them so notoriously hard to reproduce:

1. Asynchronous Race Conditions & Network Latency Spikes​

The user taps a button while an HTTP request is still in flight. A fast 5G connection in your office resolves the promise in 80 milliseconds. But a user on a commuter train with fluctuating 4G encounters a 1,800-millisecond latency spike. During that delay, they tap the button a second time, background the app to check an SMS verification code, and return. The response arrives when the UI fragment is already detached. The crash happens in an Android lifecycle callback, but the root cause was the unhandled button re-tap during a cellular latency spike.

2. Silent Failures, ANRs, and UI Freezes (App Hangs)​

A staggering percentage of release regressions never generate a fatal exception.

  • Android ANRs (Application Not Responding): The main thread stalls on disk I/O, lock contention, or heavy computation for more than 5 seconds.
  • iOS App Hangs: The main run loop blocks, rendering touch targets completely unresponsive.
  • Network Dead-Ends: An API responds with a 404 or 500 error that was swallowed in a generic try/catch block, leaving the loading spinner spinning indefinitely.

Because the operating system didn't terminate the process with a fatal signal, traditional crash loggers record either nothing or an unhelpful system thread dump that points to an idle OS loop.

3. The Breadcrumb Noise Problem​

Some APM tools attempt to capture "breadcrumbs," but they typically suffer from two extremes:

  • The Firehose: Millions of unindexed log lines that pollute dashboards, cost a fortune in ingestion fees, and drown engineers in useless console chatter.
  • The Desert: Generic system events like Activity Resumed without details on button clicks, touch targets, memory pressure, or offline state changes.

When a regression strikes, engineers don't need a million lines of unstructured text. They need a clean, chronological flight recorder that reconstructs the exact user footsteps prior to the failure.

What is Appxiom's Activity Trail? The Black Box Flight Recorder for Apps​

Appxiom was engineered to eliminate the "Cannot Reproduce" ticket entirely.

At the heart of Appxiom's diagnostic engine is the Activity Trail: a chronologically ordered, high-fidelity timeline of events, user interactions, lifecycle shifts, and network state changes captured immediately prior to any issue occurrence.

[!NOTE] What is an Activity Trail?
An Activity Trail is a chronologically ordered, microsecond-accurate timeline of user interactions (taps, clicks, gestures), screen and component lifecycle transitions, network connectivity changes, and custom developer markers captured immediately prior to an issue occurrence. It enables engineers to retrace exact user steps and reproduce release regressions without guesswork or screen recordings.

When an issue occurs - whether it is an uncaught exception, a memory leak, an ANR, an iOS App Hang, or an API failure - Appxiom packages the stack trace together with the preceding Activity Trail.

Developers and QA teams can open the issue report in the Appxiom dashboard and immediately inspect the exact breadcrumb trail leading up to the failure.

The Four Pillars of the Activity Trail​

Unlike ad-hoc logging solutions that require writing boilerplate logging statements across every view, the Activity Trail is built on four automated capabilities:

1. Auto-Tracked User Interactions​

Appxiom automatically captures UI touch events - clicks, taps, button presses, and gestures - without requiring developers to manually bind click listeners or insert logging hooks.

When a customer encounters a regression, you don't have to wonder whether they tapped "Submit", "Cancel", or the back arrow. The Activity Trail explicitly records:

  • App:TextButton - 'view order' tapped
  • App:ElevatedButton - 'Get Location' tapped
  • App:ElevatedButton - 'Place Order' tapped

2. Screen Navigation & Lifecycle Transitions​

Mobile state corruption almost always stems from screen transitions and lifecycle changes. Appxiom automatically records:

  • Activity and Fragment lifecycle events in Android (onCreate, onStart, onResume, onPause, onDestroy).
  • UIViewController lifecycle events in iOS (viewDidLoad, viewWillAppear, viewDidAppear).
  • Widget and component mounts in Flutter and React Native.
  • Foreground/background transitions (e.g., when the user switches apps or locks their screen).

3. Environment & Network State Changes​

Network connectivity on mobile devices is inherently unstable. Appxiom monitors device connectivity state changes and captures:

  • When the device drops from Wi-Fi to Cellular or goes completely offline.
  • When connectivity is restored.
  • Outgoing HTTP and HTTPS requests, including target endpoints, HTTP methods, latency in milliseconds, and status codes (e.g., 200 OK (86ms) or 404 Not Found (142ms)).

4. Custom Developer Markers (Ax.setActivityMarker)​

While auto-tracking captures the technical and UI baseline, developers often need to stamp domain-specific business context into the trail.

Appxiom provides a clean, single-line API that can be called anywhere in your codebase:

// Android (Kotlin)
Ax.setActivityMarker(this@CheckoutActivity, "checkout_step_coupon_applied: SUMMER26")
// iOS (Swift)
Ax.setActivityMarkerAt(self, marker: "biometric_authentication_verified")
// Flutter
Ax.setActivityMarker("cart_recalculated_with_tax: $total");

These custom markers are woven directly into the chronological stream alongside taps, screen transitions, and HTTP calls.

Activity Trail vs. Heavy Session Replay: Why Lightweight Breadcrumbs Win​

A common question engineers ask is: "Why not just use a full session replay tool like LogRocket, FullStory, or Sentry Session Replay?"

While session replay video recordings sound appealing on paper, engineering teams frequently abandon them in mobile production for several critical reasons:

Feature / ConsiderationHeavy Session Replay ToolsAppxiom Activity Trail
CPU & Frame Rate ImpactHigh (captures DOM/Canvas frames, causes UI jank)Zero (idle-frame execution, smooth 60/120fps)
Network & Battery DrainHeavy (megabytes of compressed video/wireframes)Negligible (ultra-compressed text payloads)
Data Privacy & PII RiskHigh risk of leaking passwords, cards, or user dataZero PII by design (captures events, not inputs)
Offline ResilienceBuffers fail or drop video chunks on bad networksSandboxed local cache with seamless resend
Engineering SignalRequires watching 5-minute videos to find a bugInstant 10-second scan of the exact causal chain

Activity Trail gives developers the precise technical forensics they need to fix code without the privacy nightmares, compliance headaches, or performance penalties of video replays.

Visualizing the Crime Scene: Chronological Activity Trail Walkthrough​

Below is an example of what an engineer sees in the Appxiom dashboard when inspecting an issue report. Notice how each event includes a microsecond-accurate timestamp, event category, event payload, and the device's free memory percentage at that exact moment:

APPXIOM ACTIVITY TRAIL TIMELINE

Issue: POST /api/v2/orders/process → 409 Conflict
Exception: IllegalStateException: Order already locked
Version: v4.2.0 (Build 184) | Device: Google Pixel 8 | OS: Android 15

TIMECATEGORYEVENT DETAILSFREE MEM
10:14:02.115LIFECYCLECartActivity:onResume48.2%
10:14:03.450USER ACTIONClicked "Apply Promo Code"48.0%
10:14:03.538HTTPPOST /api/v2/promos/validate → 200 OK (88ms)47.9%
10:14:04.102CUSTOMAx.setActivityMarker: promo_applied_SUMMER2647.9%
10:14:06.890USER ACTIONClicked "Proceed to Checkout"47.5%
10:14:07.012LIFECYCLECheckoutActivity:onCreate46.8%
10:14:07.410LIFECYCLECheckoutActivity:onResume46.8%
10:14:08.115NETWORKWIFI → CELLULAR_OFFLINE46.8%
10:14:08.840USER ACTIONClicked "Place Order" (Tap 1)46.5%
10:14:09.120USER ACTIONClicked "Place Order" (Tap 2)46.5%
10:14:09.650NETWORKCELLULAR_OFFLINE → 4G_ONLINE46.4%
10:14:10.200HTTPPOST /api/v2/orders/process → 200 OK (110ms)46.2%
10:14:10.315HTTPPOST /api/v2/orders/process → 409 Conflict (98ms)46.2%
10:14:10.420ISSUEIllegalStateException: Cannot process duplicate46.1%

Dissecting the Crime Scene in Under 60 Seconds​

Without the Activity Trail, all the engineer would see is a stack trace showing IllegalStateException: Cannot process duplicate order at CheckoutActivity.kt:188.

The engineer would spend days trying to understand why duplicate orders are being sent. Is the backend caching stale idempotency tokens? Is Retrofit duplicating headers?

With the Activity Trail, the answer is immediately obvious:

  1. At 10:14:08.115, the user's connection dropped to offline.
  2. The user tapped 'Place Order'. Nothing visibly happened because the request was queued.
  3. Frustrated, the user tapped 'Place Order' a second time at 10:14:09.120.
  4. Half a second later, network connectivity was restored.
  5. Both queued requests fired simultaneously. The first succeeded (200 OK), but the second was rejected by the server (409 Conflict).
  6. The client code lacked button debouncing and did not handle the 409 conflict gracefully, triggering an unhandled exception.

Time to diagnose: 45 seconds.
Fix: Add a UI debounce on the checkout button and catch 409 status responses to show an idempotent confirmation banner.

Solving Three Infuriating Release Regressions with Activity Trail​

Let's look at three notorious categories of regressions that plague engineering teams and how Activity Trail resolves them.

Case 1: State Restoration & Race Conditions After App Backgrounding​

The Bug: Users complain that after receiving a phone call or switching to their banking app to copy a one-time password (OTP), returning to your app causes a blank screen or a crash.

Why It's a Nightmare to Reproduce: On developer devices, Android and iOS have ample RAM. When you switch apps during testing, your application remains alive in memory. But in production, users with 20 background apps, low-end devices, or aggressive OEM battery optimizers experience immediate process death.

How Activity Trail Solves It: The trail clearly records:

14:22:10.100  LIFECYCLE    PaymentActivity:onPause
14:22:10.350 LIFECYCLE PaymentActivity:onStop
14:22:10.400 LIFECYCLE App went to BACKGROUND
14:22:35.800 LIFECYCLE App returned to FOREGROUND
14:22:36.100 LIFECYCLE PaymentActivity:onCreate (savedInstanceState != null)
14:22:36.210 ISSUE NullPointerException: ViewModelFactory not initialized

The developer instantly realizes: the activity restoration flow assumed the DI singleton was still warm. When the OS killed the process in the background, onCreate ran with a non-null savedInstanceState, but the singleton was re-initialized to null.

Case 2: Silent ANRs and UI Freezes on the Main Thread​

The Bug: Google Play Console flags a spike in your ANR rate, threatening your app's search visibility and store ranking. The trace provided by Google Play Vitals simply says:

"main" prio=5 tid=1 Native
#00 pc 000000000004b344 /apex/com.android.runtime/lib64/bionic/libc.so (syscall+28)
#01 pc 00000000001ae4f8 /apex/com.android.art/lib64/libart.so (art::ConditionVariable::WaitHoldingLocks)

This tells you the main thread was waiting on a lock. Which lock? Triggered by what? Google Play Vitals cannot tell you.

How Activity Trail Solves It: In Appxiom, the ANR issue report displays the chronological trail right before the freeze:

12:22:50.110  USER ACTION  Clicked - button - 'Filter Transactions'
12:22:50.215 CUSTOM Ax.setActivityMarker: filter_dataset_size_45000_items
12:22:50.220 LIFECYCLE TransactionListFragment:onPause
12:22:55.300 ISSUE ANR Detected: Main thread blocked for 5,080ms

The correlation is unmistakable: the user clicked 'Filter Transactions' with a dataset of 45,000 items. The sorting operation ran synchronously on the main thread instead of being offloaded to Dispatchers.Default or a background worker.

Case 3: Progressive Memory Leaks Disguised as Out-Of-Memory Crashes​

The Bug: You see an OutOfMemory (OOM) crash on a simple profile update screen. Developers insist: "There's no way updating an avatar consumes 512 MB of heap!"

How Activity Trail Solves It: Because Appxiom records the free memory percentage with every single lifecycle event and marker, you can trace the memory trajectory over time:

09:15:10  ProductDetailActivity:onCreate       54.2% FREE MEMORY
09:15:32 ProductDetailActivity:onDestroy 48.1% FREE MEMORY
09:16:04 ProductDetailActivity:onCreate 41.3% FREE MEMORY
09:16:28 ProductDetailActivity:onDestroy 35.0% FREE MEMORY
09:17:02 ProductDetailActivity:onCreate 28.4% FREE MEMORY
09:17:40 ProductDetailActivity:onDestroy 21.1% FREE MEMORY
09:18:12 ProfileActivity:onCreate 12.5% FREE MEMORY
09:18:15 ISSUE: java.lang.OutOfMemoryError 4.1% FREE MEMORY

The profile screen didn't cause the leak. The ProductDetailActivity was failing to unregister an image caching listener, leaking 30 MB of bitmap memory every time it was opened. The profile screen was merely the unlucky innocent bystander when memory ran out.

Instrumenting Activity Trail Across Android, iOS, and Flutter​

Instrumenting your application with Appxiom doesn't require rewriting your codebase. The SDK is engineered for effortless setup and zero friction.

Android (Kotlin & Java)​

import com.appxiom.android.Ax

class CheckoutActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_checkout)

// Custom marker that appears in the Activity Trail
Ax.setActivityMarker(this, "entered_checkout_flow")

// Debug-only marker (automatically stripped from release builds)
Ax.setActivityMarkerForDebug(this, "debug_cart_hash: ${cart.hashCode()}")
}
}

ProGuard & R8 Protection: When using aggressive code shrinking and obfuscation, class names in standard crash reports turn into unreadable alphabet soup (a.b.c). Appxiom provides the @AX annotation to maintain human-readable identifiers in your Activity Trail even in release builds:

@AX("CheckoutScreen")
class CheckoutActivity : AppCompatActivity() { ... }

iOS (Swift & SwiftUI)​

import Appxiom

class PaymentViewController: UIViewController {

override fun viewDidLoad() {
super.viewDidLoad()

// Single-line marker injection
Ax.setActivityMarkerAt(self, marker: "stripe_payment_sheet_presented")
}

@IBAction func didTapPayButton(_ sender: UIButton) {
Ax.setActivityMarkerAt(self, marker: "pay_button_pressed")
processPayment()
}
}

Flutter (Dart)​

import 'package:appxiom_flutter/appxiom_flutter.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();

// Initialize Appxiom for Android & iOS
Ax.init("android_app_key", "android_platform_key");
Ax.initIOS();

// Wrap app runner for automatic widget and navigation tracking
AxApp.run(
child: const MyApp(),
screenName: 'MainApp',
widgetName: 'MyApp',
);
}

// Anywhere in your business logic:
Ax.setActivityMarker("user_applied_filter_category_electronics");

Production Reliability: Idle-Frame Processing, Offline Sandboxing, and Zero-PII Privacy​

Mobile engineers are rightly skeptical of third-party SDKs that monitor user interactions. If a diagnostic tool causes frame drops or drains the battery, it becomes part of the problem.

Appxiom was designed with three strict production guarantees:

1. Idle-Frame Execution​

Data collection, timestamp calculation, and event buffering run strictly during CPU idle frames. Event batching never interrupts the UI rendering pipeline, ensuring your 60fps and 120fps ProMotion animations remain buttery smooth.

2. Offline Sandbox Buffering​

Mobile users enter tunnels, board subways, and toggle airplane mode. When network connectivity drops, Appxiom securely caches breadcrumbs and activity markers in a local sandbox. Once connectivity is re-established, the data is compressed, batched, and transmitted in the background without dropping a single event.

3. Privacy-First by Design​

Appxiom tracks interaction geometry, button identifiers, and component lifecycles. It never captures sensitive user keystrokes, passwords, or PII. You get the technical context required to reproduce the defect without compromising user privacy or violating GDPR and CCPA compliance.

Beyond Isolated Fixes: Version Analytics, Quality Score, and Release Regression Prevention​

The Activity Trail is a powerful debugging tool for individual bugs, but its true superpower emerges when connected to Appxiom's full observability suite:

  1. Appxiom Quality Score (QS): Evaluates release health on a unified 0–10 scale across crashes, ANRs, app hangs, and latency. If your Quality Score drops immediately after a release, you know a regression has hit production.
  2. Goal Friction Impact (GFI): Quantifies exactly how much money and conversion volume a regression is costing your business by measuring drop-offs in critical funnels (signups, subscriptions, purchases).
  3. Version Analytics: Compares error distributions across releases to verify whether a hotfix genuinely resolved the targeted regression without introducing secondary anomalies.
  4. Activity Trail: Provides the engineering team with the exact user footsteps needed to replicate, diagnose, and fix the root cause immediately.

Instead of arguing in cross-functional meetings about whether a bug is reproducible or how severe it is, engineering, QA, and product teams have a shared, unambiguous timeline of reality.

Stop Guessing. Start Reproducing.​

Every hour your engineering team spends guessing how an edge case happened is an hour stolen from building features that grow your product.

Every ticket closed as "Cannot Reproduce" is a ticking time bomb waiting to detonate in your app store ratings.

With Appxiom's Activity Trail, you never have to ask:

  • "What did the user click before it crashed?"
  • "Can QA get a screen recording?"
  • "Why doesn't this happen on my machine?"

You open the issue, read the trail, and fix the bug.

Ready to Eliminate "Cannot Reproduce" From Your Sprints?​

Stop letting release regressions derail your team's momentum. See how Appxiom's Activity Trail, Quality Score, and Goal Friction Impact give mobile teams superpowers.

Start Your Free Appxiom Trial Today or explore our comprehensive documentation to see how easy integration really is.

Why Function Tracking is the Better Approach to Mobile App Bug Reporting

Published: · Last updated: · 4 min read
Andrea Sunny
Marketing Associate, Appxiom

If you have worked on a mobile app for any amount of time, you already know one thing. Bug reporting is often frustrating. You get a crash log. You get a network error. You get a stack trace that points to the very end of a problem. And then you are left trying to guess everything that happened before that moment.

It feels like walking into a movie three minutes before it ends and trying to guess the entire story.

That is the reality of traditional bug reporting.

Now imagine something different. Imagine being able to see exactly what your app was doing inside its functions. You could see what input it received, how it behaved, where things slowed down, and what actually caused the issue. That is the idea behind function tracking. And once you understand it, you can clearly see why it is a far better approach.

App Hangs in iOS: Causes, Code Fixes, and How to Spot Them

Published: · Last updated: · 5 min read
Don Peter
Cofounder and CTO, Appxiom

Ever tapped a button in your app and waited... and waited... until you started questioning your life choices?

Yeah, that's an app hang.

It's not a crash. It's worse. Your app doesn't explode, it just freezes. Quietly. Awkwardly. Like someone forgot their lines on stage and now the whole audience is staring.

App hangs are sneaky. They don't always show up in crash reports. But your users feel them. In the lags, the unresponsive screens, the moments when they swipe but nothing moves. And if it happens too often? That uninstall button starts looking real attractive.

But it doesn't have to be that way.

Let's fix the freeze before the curtain falls.

How to Detect and Fix Android Memory Leaks Before They Crash Your App

Published: · Last updated: · 4 min read
Andrea Sunny
Marketing Associate, Appxiom

Have you ever dated someone who just… wouldn't let go?

You break up, move on, start fresh - and boom - they're still texting, still showing up in your life, refusing to be deleted.

That's your app with a memory leak.

It's holding on to screens, data, and objects long after it should've moved on. You've moved past the Activity, but it's still lingering in memory like a clingy ex who didn't get the memo.

The worst part? You might not even know it's happening.

But users will. They will feel it in the slowdowns, the crashes, the app that once felt smooth now feeling… emotionally unavailable.

And in Android, they're not just annoying. They're dangerous. They can slow down your app, cause freezes, and eventually - boom! A crash.

Let's dive into the most common memory leak scenarios in Android. I'll walk you through real-world examples, show you how to spot them, and most importantly, how to fix them.

Smarter iOS App Testing with BrowserStack and Appxiom

Published: · Last updated: · 6 min read
Andrea Sunny
Marketing Associate, Appxiom

You're test-driving a car. Everything seems fine, until you hit 60 mph and the steering wheel starts shaking. Weird, right? You take it back to the shop, only to hear, "Oh, that only happens on highways. We didn't test for that."

Now imagine that same moment, but with your iOS app. It passes all your tests locally. Looks great on your simulator. But when it lands in the real world? Crash on iOS 16.3. A layout glitch on the iPhone SE. A memory spike on iPadOS.

Here comes your first comment, "App keeps crashing when I switch tabs. iOS 16.3."

And boom! Your 5-star rating dips, users uninstall, and your team scrambles in damage-control mode.

That's why modern iOS teams don't just test. They test right.

Let's talk about Appxiom + BrowserStack - a killer combo that brings you deep device coverage and smart issue detection in one efficient workflow.

What is BrowserStack?​

BrowserStack is your all-access pass to testing iOS apps on real devices, without needing to build your own hardware lab. From the latest iPhones to older iPads running quirky iOS versions, it gives you cloud-based access to actual devices (not emulators), so you can run both manual and automated tests with ease. Think of it as having a fully-stocked Apple device warehouse right in your browser. Whether you're running regression tests or checking cross-device compatibility, BrowserStack helps you ensure your app looks sharp and works flawlessly, no matter where or how your users open it.

What Is Appxiom?​

Now here's where Appxiom steps in, and turns up the heat in the best way possible.

Appxiom is a real-time issue detection platform that helps you catch crashes, performance drops, and user-impacting bugs during testing, before your users ever see them.

If BrowserStack shows you where your app might stumble, Appxiom shows you why. While your tests run across real iOS devices, Appxiom is silently at work in the background, listening in on everything that happens beneath the surface.

Crashes during navigation? It catches them. Memory leaks hiding behind a clean UI? Detected. Janky scrolls, sluggish taps, or performance drops? Marked. Bugs that quietly kill conversions? Flagged with business impact.

Appxiom doesn't just collect this data, it translates it into rich, actionable insights. You get real-time issue reports that include severity, device context, and user flow impact, all wrapped in a developer-friendly dashboard. Instead of digging through logs or guessing what went wrong, you know exactly what to fix, and why it matters.

The result? You stop reacting to bug reports after users complain and start resolving issues before they ever hit production. With Appxiom riding alongside your BrowserStack tests, every test session becomes a proactive debugging session. It's like running your app through an MRI while it performs on stage-and getting the results instantly.

How to Integrate BrowserStack and Appxiom Together for Smarter iOS Testing​

Here's how to integrate BrowserStack and Appxiom into your iOS workflow:

Step 1: Setting Up BrowserStack​

Head to browserstack.com and create your account. Explore their documentation to understand device setup, automation tools, and test configuration. Install required SDKs and dependencies for running your iOS tests.

Step 2: Integrating Appxiom​

Register with Appxiom at appxiom.com and log in to the dashboard. Click "Add App" to connect your iOS app. Follow integration steps in the Appxiom Docs to embed the Appxiom framework into your app. Run a quick sanity test to make sure the integration is successful.

Step 3: Running Tests on BrowserStack​

Choose your target iPhones or iPads from BrowserStack's real device lab. Configure the test environment and load your Appxiom-integrated app. Use your test framework to run automated test cases. Monitor UI behavior, response times, and user flow - all in real-time.

Step 4: Analyzing Appxiom Reports​

Log in to your Appxiom dashboard after running tests on BrowserStack. Identify performance issues, crashes, UI glitches, or slowdowns detected during testing. Review detailed bug reports with data points like issue type, severity, device info, and timestamps. Use these insights to reproduce and resolve bugs quickly.

The Power of Pairing: Why BrowserStack + Appxiom Just Makes Sense​

Imagine this: You're testing your iOS app on a real iPhone 14 using BrowserStack. Everything looks smooth on the surface. But beneath that pixel-perfect UI, Appxiom is quietly watching for deeper issues - things no visual test would catch.

That's the beauty of using both tools together. One handles the "outside," the other handles the "inside." And when paired, they give you something every developer dreams of: complete visibility.

Here's what you really get when you bring them together:

1. Enhanced Device Coverage​

With BrowserStack, you're testing on actual iOS hardware. No flaky emulators, no simulator - only bugs. You see what your users see.

2. Silent Bug Surveillance​

Silent killers like API issues, memory spikes, UI jank usually go undetected until it's too late. Appxiom flags them in real time, even if no one reports them.

3. Crystal-Clear Reproduction​

When a bug appears, Appxiom shows you where, how, and why it happened, right down to the device, OS version, and line of code. Combine that with BrowserStack's stable testing environment, and reproducing bugs becomes effortless.

4. Fix What Matters, Fast​

Not all bugs deserve a panic patch. Appxiom tells you which ones are impacting your users the most, so you prioritize smart, not out of fear.

5. Save Time. Save Budget. Save Face.​

No more post-release chaos. With better pre-release coverage and proactive detection, you catch problems early, and avoid costly fixes later.

In Summary​

Testing on real devices? Necessary. Catching hidden bugs before users do? Priceless.

With BrowserStack, you test how your app looks and behaves. With Appxiom, you understand how it performs and fails, even when it looks fine.

Together? You've got a world-class iOS testing workflow that keeps your app sharp, your users happy, and your team confident.

Start using Appxiom with BrowserStack today!

Because flawless apps aren't built by chance. They're built by choice.

How to Manage UX When a Bug Occurs in Your Android App

Published: · Last updated: · 5 min read
Andrea Sunny
Marketing Associate, Appxiom

You're out for dinner. Ambience? Perfect. Service? Spot on. Then your dish arrives. But something's off. The pasta's missing salt, or the steak's slightly overcooked. You raise your hand to get the waiter's attention. But before you can say a word, they smile and say, "The chef already noticed. A fresh plate is on its way."

It feels like magic. But really, it's just attention to detail before a complaint even happens.

That's the kind of experience your users expect from your app too. Silent problems fixed before they even realize something went wrong.

How to Avoid Memory Leaks in Jetpack Compose

Published: · Last updated: · 4 min read
Appxiom Team
Mobile App Performance Experts

Jetpack Compose is a modern Android UI toolkit introduced by Google, designed to simplify UI development and create more efficient and performant apps. While it offers numerous advantages, like a declarative UI syntax and increased developer productivity, it's not immune to memory leaks.

Memory leaks in Android can lead to sluggish performance and even app crashes. In this blog post, we'll explore the possibilities of causing memory leaks in Jetpack Compose and common reasons behind them. We'll also provide code examples and discuss strategies to prevent and fix these issues.

Understanding Memory Leaks​

Before diving into Jetpack Compose-specific issues, let's briefly understand what a memory leak is. A memory leak occurs when objects that are no longer needed are not released from memory, causing a gradual increase in memory consumption over time. In Android, this is typically caused by retaining references to objects that should be garbage collected.

How to Avoid Memory Leaks in Jetpack Compose​

1. Lambda Expressions and Captured Variables​

Jetpack Compose heavily relies on lambda expressions and function literals. When these lambdas capture references to objects, they can unintentionally keep those objects in memory longer than necessary. This often happens when lambdas capture references to ViewModels or other long-lived objects.

@Composable
fun MyComposable(viewModel: MyViewModel) {
// This lambda captures a reference to viewModel
Button(onClick = { viewModel.doSomething() }) {
Text("Click me")
}
}

In this example, the lambda passed to Button captures a reference to the viewModel parameter. If MyComposable gets recomposed, a new instance of the lambda will be created, but it still captures the same viewModel reference. If the old MyComposable instance is no longer in use, the captured viewModel reference will keep it from being garbage collected, potentially causing a memory leak.

To avoid this, you can use the remember function to ensure that the lambda captures a stable reference:

@Composable
fun MyComposable(viewModel: MyViewModel) {
val viewModelState by remember { viewModel.state }

Button(onClick = { viewModelState.doSomething() }) {
Text("Click me")
}
}

Here, remember is used to cache the value of viewModel.state. This ensures that the lambda inside Button captures a stable reference to viewModelState. As a result, even if MyComposable is recomposed, it won't create unnecessary new references to viewModel, reducing the risk of memory leaks.

2. Composable Functions and State​

Composables are functions that can rebuild when their inputs change. If you're not careful, unnecessary recompositions can lead to memory leaks. Composable functions that create and hold onto state objects, especially those with a long lifecycle, can cause memory leaks.

@Composable
fun MyComposable() {
val context = LocalContext.current
val database = Room.databaseBuilder(context, MyDatabase::class.java, "my-database").build()

// ...
}

To mitigate this, prefer creating and closing resources within a DisposableEffect:

@Composable
fun MyComposable() {
val context = LocalContext.current

DisposableEffect(Unit) {
val database = Room.databaseBuilder(context, MyDatabase::class.java, "my-database").build()
onDispose {
database.close()
}
}

// ...
}

​

3. Forgetting to Dispose of Observers​

Jetpack Compose's LiveData and State are commonly used for observing and updating UI. However, not removing observers correctly can result in memory leaks. When a Composable is removed from the UI hierarchy, you should ensure that it no longer observes any LiveData or State.

@Composable
fun MyComposable(viewModel: MyViewModel) {
val data = viewModel.myLiveData.observeAsState()

// ...
}

To address this, use the DisposableEffect to automatically remove observers when the Composable is no longer needed:

@Composable
fun MyComposable(viewModel: MyViewModel) {
DisposableEffect(viewModel) {
val data = viewModel.myLiveData.observeAsState()
onDispose {
// Remove observers or do necessary cleanup here
}
}

// ...
}

Conclusion​

Jetpack Compose is a powerful tool for building modern Android user interfaces. However, like any technology, it's essential to be aware of potential pitfalls, especially regarding memory management.

By understanding the common causes of memory leaks and following best practices, you can create efficient and performant Compose-based apps that delight your users.

Testing Kotlin Based Android Apps

Published: · Last updated: · 9 min read
Appxiom Team
Mobile App Performance Experts

Testing is an integral part of the software development process, and Android app development is no exception. Kotlin, being the official programming language for Android development, provides developers with powerful tools and frameworks for testing Android apps.

In this blog, we will explore various testing strategies and best practices for testing Kotlin Android apps, ensuring high-quality and robust applications.

1. Setting up the Testing Environment​

Before diving into testing, you need to set up the testing environment for your Kotlin Android app. This involves adding the necessary dependencies and libraries and determining the types of tests you'll perform.

1.1. Dependencies and Libraries​

To enable testing, include the following dependencies in your app's build.gradle file:

dependencies {
// Testing dependencies
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.4.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
// Other dependencies...
}

1.2. Test Types​

There are three main types of tests in Android app development:

  • Unit Tests: Focus on testing individual components in isolation, such as functions, classes, or modules.

  • Instrumented Tests: Run on an Android device or emulator and interact with the app's UI components and resources.

  • Automated UI Tests: Similar to instrumented tests but are written to simulate user interactions and test user flows automatically.

Now that the testing environment is set up let's move on to the different testing strategies.

2. Unit Testing​

Unit testing involves testing individual components of your app in isolation to ensure that they function correctly.

2.1. Introduction to Unit Testing​

Unit tests focus on testing small units of code, such as individual functions or classes. They help identify bugs early in the development process, improve code maintainability, and provide fast feedback during development.

2.2. Writing Unit Tests in Kotlin​

To write unit tests in Kotlin, you can use the JUnit testing framework. Write test methods that assert the expected behavior of the code being tested.

For example, test a function that calculates the sum of two numbers:

import org.junit.Test
import org.junit.Assert.assertEquals

class MathUtilsTest {
@Test
fun testSum() {
val result = MathUtils.sum(2, 3)
assertEquals(5, result)
}
}

2.3. Using Mockito for Mocking Dependencies​

Sometimes, unit tests require mocking dependencies to isolate the code being tested. Mockito is a popular mocking framework that simplifies the creation of mock objects. It allows you to define the behavior of mock objects and verify interactions with them.

For example:

import org.junit.Test
import org.junit.Assert.assertEquals
import org.mockito.Mockito.*

class UserManagerTest {
@Test
fun testUserCreation() {
val userService = mock(UserService::class.java)
val userManager = UserManager(userService)

`when`(userService.createUser("John Doe")).thenReturn(User("John Doe"))

val user = userManager.createUser("John Doe")

assertEquals("John Doe", user.name)
verify(userService).createUser("John Doe")
}
}

2.4. Running Unit Tests​

To run unit tests, right-click on the test class or package in Android Studio and select "Run 'ClassName'" or "Run 'PackageName'." You can also use Gradle commands like ./gradlew test to run tests from the command line.

3. Instrumentation Testing​

Instrumentation tests allow you to test your app's behavior on an Android device or emulator. These tests interact with the app's UI components, resources, and the Android framework.

3.1. Introduction to Instrumentation Testing​

Instrumentation tests are essential for verifying the correct behavior of your app's UI and interactions with the underlying system. They help catch bugs related to UI rendering, user input handling, and inter-component communication.

3.2. Writing Instrumented Tests in Kotlin​

To write an instrumented test in Kotlin, use the androidx.test framework. Create a test class and annotate it with @RunWith(AndroidJUnit4::class). Use the @Test annotation on individual test methods.

For example:

import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.ActivityTestRule
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class MainActivityInstrumentedTest {
@Rule@JvmField
val activityRule = ActivityTestRule(MainActivity::class.java)

@Test
fun testButtonClick() {
val appContext = InstrumentationRegistry.getInstrumentation().targetContext

// Simulate a button click
onView(withId(R.id.button)).perform(click())

// Verify the expected text is displayed
onView(withId(R.id.textView)).check(matches(withText("Button Clicked")))
}
}

3.3. Running Instrumented Tests​

To run instrumented tests, right-click on the test class or package in Android Studio and select "Run 'ClassName'" or "Run 'PackageName'." You can also use Gradle commands like ./gradlew connectedAndroidTest to run instrumented tests from the command line.

3.4. Interacting with UI Elements​

The androidx.test.espresso library provides a fluent and expressive API for interacting with UI elements in instrumented tests. Use methods like onView, perform, and check to find views and perform actions on them.

For example, onView(withId(R.id.button)).perform(click()) simulates a click on a button with the specified ID.

3.5. Using Espresso for UI Testing​

Espresso is a popular testing framework within androidx.test.espresso for UI testing. It simplifies writing concise and readable tests for Android UI components. Espresso provides a rich set of matchers, actions, and assertions.

For more details, visit the link provided at the end of this blog [1].

4. Automated UI Testing​

Automated UI tests, also known as end-to-end tests, simulate user interactions and test user flows automatically. These tests ensure that different parts of the app work together correctly.

4.1. Introduction to Automated UI Testing​

Automated UI tests simulate user interactions, such as button clicks, text input, and gestures, to test the app's behavior and flow. These tests help catch integration issues, data flow problems, and user experience regressions.

4.2. Writing Automated UI Tests in Kotlin​

To write automated UI tests in Kotlin, you can use frameworks like Espresso or UI Automator. Create test classes and use the testing APIs to interact with UI elements and perform actions.

For example:

import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import org.junit.Test

class MainActivityAutomatedTest {
@Test
fun testButtonClick() {
ActivityScenario.launch(MainActivity::class.java)

// Simulate a button click
onView(withId(R.id.button)).perform(click())

// Verify the expected text is displayed
onView(withId(R.id.textView)).check(matches(withText("Button Clicked")))
}
}

4.3. Running Automated UI Tests​

To run automated UI tests, follow the same process as running instrumented tests. Right-click on the test class or package in Android Studio and select "Run 'ClassName'" or "Run 'PackageName'." Use Gradle commands like ./gradlew connectedAndroidTest to run tests from the command line.

4.4. Testing Navigation and User Flows​

Automated UI tests are ideal for testing navigation and user flows within your app. Simulate user interactions to move between screens, verify correct data flow, and validate the expected behavior at each step.

5. Test Doubles and Dependency Injection​

Test doubles are objects used in place of real dependencies during testing. Dependency Injection (DI) helps manage dependencies and facilitates the use of test doubles.

5.1. Understanding Test Doubles​

Test doubles include stubs, mocks, fakes, and dummies. They allow you to isolate code under test, simulate specific behaviors, and verify interactions. Use test doubles to replace external dependencies or collaborator objects.

5.2. Using Dependency Injection for Testability​

Design your app with dependency injection principles in mind. Dependency injection frameworks like Dagger or Koin can help manage dependencies and make testing easier. Inject test doubles instead of real dependencies during testing.

5.3. Mocking Dependencies with DI Containers​

DI containers, such as Mockito or Koin, provide mechanisms to define test-specific configurations and replace real dependencies with test doubles. Use these containers to inject mock objects and stub behaviors.

5.4. Configuring Test-Specific Dependencies​

Configure your DI container to provide test-specific dependencies when running tests. This allows you to control the behavior of dependencies during testing and ensure predictable test results.

6. Test Coverage and Continuous Integration​

Test coverage measures the extent to which your code is tested by your test suite. Continuous Integration (CI) ensures that your tests are run automatically and regularly as part of your development workflow.

6.1. Measuring Test Coverage​

Use tools like JaCoCo or Android Studio's built-in code coverage to measure test coverage. Aim for high code coverage to ensure that critical parts of your app are adequately tested.

6.2. Configuring Continuous Integration (CI)​

Set up a CI system, such as Jenkins, Travis CI, or CircleCI, to automatically build and test your app. Configure your CI pipeline to run your tests and generate test reports.

6.3. Running Tests on CI Platforms​

Configure your CI system to execute your tests during the build process. Ensure that your build script or CI configuration includes the necessary commands to run unit tests, instrumented tests, and automated UI tests.

7. Using APM Tools​

APM tools play a crucial role in monitoring and analyzing the performance and stability of your Kotlin Android apps. They provide real-time insights into crashes, errors, and performance bottlenecks, helping you identify and resolve issues quickly.

Some of the popular APM tools for Android apps are Bugsnag, Appxiom, New Relic and Sentry.

8. Testing Best Practices​

Follow these best practices to write effective and maintainable tests for your Kotlin Android apps:

8.1. Isolating Tests​

Each test should be independent and not rely on the state or side effects of other tests. Isolate tests to prevent dependencies between them, ensuring consistent and reliable results.

8.2. Writing Readable and Maintainable Tests​

Write tests that are easy to understand and maintain. Use descriptive method and variable names, organize tests logically, and avoid duplicating code across tests.

8.3. Using Test Fixtures​

Test fixtures are preconditions or shared resources required for multiple tests. Use setup and teardown methods, annotations, or test fixture classes to set up common test conditions and clean up resources.

8.4. Test-Driven Development (TDD)​

Consider Test-Driven Development as a development practice. Write tests before implementing functionality. This approach helps define the desired behavior, ensures testability, and provides quick feedback.

8.5. Performance Testing​

Consider performance testing to identify bottlenecks and optimize critical parts of your app. Measure performance metrics, such as response times or memory usage, to ensure your app meets performance expectations.

8.6. Edge Cases and Boundary Testing​

Test edge cases and boundary conditions, such as maximum and minimum input values or error scenarios. These tests help uncover potential issues related to limits, constraints, or exceptional situations.

Conclusion​

In this blog, we explored various testing strategies for Kotlin Android apps. We covered unit testing, instrumentation testing, automated UI testing, test doubles, dependency injection, test coverage, continuous integration, APM tools, and best practices.

By incorporating these testing strategies into your development process, you can ensure high-quality, robust, and reliable Kotlin Android apps. Remember to continuously iterate and improve your test suite to catch bugs early and deliver exceptional user experiences.

  • Testing Jetpack Compose based Android UI using Espresso.

A Comprehensive Guide on How to Test Flutter Mobile Apps

Published: · Last updated: · 6 min read
Appxiom Team
Mobile App Performance Experts

In the fast-paced world of mobile app development, ensuring the quality and reliability of your application is crucial. Flutter, a popular cross-platform framework developed by Google, has gained significant traction among developers for its ability to create stunning mobile apps for both Android and iOS platforms. Testing plays a vital role in delivering a successful Flutter app, ensuring its functionality, performance, and user experience.

In this blog post, we will explore the different aspects of testing Flutter mobile apps and provide a comprehensive guide to help you achieve a robust and reliable application.

Understanding Flutter Testing Fundamentals​

Before diving into the testing process, it's essential to familiarize yourself with the basic testing concepts in Flutter.

Flutter provides several testing frameworks and tools, including unit testing, widget testing, and integration testing. Understanding these concepts will allow you to choose the appropriate testing approach based on your application's requirements.

1. Writing Unit Tests​

Unit tests are the foundation of any test suite and focus on testing individual units of code. In Flutter, you can use the built-in test package, which provides utilities for writing and executing unit tests. Unit tests help validate the behavior of functions, classes, and methods in isolation, ensuring that they produce the expected output for a given input.

Let's take a look at an example of a unit test:

import 'package:test/test.dart';

int sum(int a, int b) {
return a + b;
}

void main() {
test('Sum function adds two numbers correctly', () {
expect(sum(2, 3), equals(5));
expect(sum(0, 0), equals(0));
expect(sum(-1, 1), equals(0));
});
}

In this example, we define a sum function that adds two numbers. We then write a unit test using the test function from the test package. The expect function is used to assert that the actual result of the sum function matches the expected result.

2. Widget Testing​

Widget testing in Flutter involves testing the UI components of your application. It allows you to verify if the widgets render correctly and behave as expected. The Flutter framework provides the flutter_test package, which offers a rich set of APIs for widget testing. With widget testing, you can simulate user interactions, verify widget states, and test widget rendering across different screen sizes and orientations.

Here's an example of a widget test:

import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/material.dart';

void main() {
testWidgets('Button changes text when pressed', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: ElevatedButton(
onPressed: () {},
child: Text('Button'),
),
),
));

expect(find.text('Button'), findsOneWidget);
await tester.tap(find.byType(ElevatedButton));
await tester.pump();

expect(find.text('Button Pressed'), findsOneWidget);
});
}

In this example, we create a widget test using the testWidgets function from the flutter_test package. We use the pumpWidget function to build and display the widget hierarchy. Then, we use the find function to locate the widget we want to interact with, and the tap function to simulate a tap on the widget. Finally, we assert that the widget's text changes to 'Button Pressed' after the tap.

3. Integration Testing​

Integration testing focuses on testing the interaction between multiple components of your application, such as different screens, databases, APIs, and external dependencies. Flutter provides a powerful testing framework called Flutter Driver, which allows you to write integration tests that interact with your app as if a real user were using it. Integration tests help identify issues related to navigation, data flow, and interactions between different parts of your app.

Here's an example of an integration test:

import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';

void main() {
FlutterDriver driver;

setUpAll(() async {
driver = await FlutterDriver.connect();
});

tearDownAll(() async {
if (driver != null) {
driver.close();
}
});

test('Login and navigate to home screen', () async {
await driver.tap(find.byValueKey('username_field'));
await driver.enterText('john_doe');
await driver.tap(find.byValueKey('password_field'));
await driver.enterText('password123');
await driver.tap(find.byValueKey('login_button'));

await driver.waitFor(find.byValueKey('home_screen'));
});
}

In this example, we use the flutter_driver package to write an integration test. We set up a connection to the Flutter driver using the FlutterDriver.connect method. Then, we define a test that simulates a login flow by interacting with various widgets using the tap and enterText methods. Finally, we assert that the home screen is successfully displayed.

Test-Driven Development (TDD)​

Test-Driven Development is a software development approach that emphasizes writing tests before writing the actual code. With TDD, you define the desired behavior of your app through tests and then write code to fulfill those test requirements. Flutter's testing tools and frameworks integrate seamlessly with TDD practices, making it easier to build reliable and maintainable applications. By writing tests first, you ensure that your code is thoroughly tested and behaves as expected.

Continuous Integration and Delivery (CI/CD)​

Incorporating a robust CI/CD pipeline for your Flutter app is crucial to automate the testing process and ensure consistent quality across different stages of development. Popular CI/CD platforms like Jenkins, CircleCI, and GitLab CI/CD can be integrated with Flutter projects to run tests automatically on every code commit or pull request.

Additionally, you can leverage tools like Firebase Test Lab to test your app on various physical and virtual devices, ensuring compatibility and performance across different configurations.

Using Tools for Testing​

Using tools like Firebase, Instabug, BugSnag and Appxiom to detect performance issues and other bugs will help you in detecting bugs which may otherwise go undetected in manual testing. They provide detailed bug reports with data that will help you to reproduce the bug and identify the root cause.

Conclusion​

Testing is an integral part of the Flutter app development process, ensuring that your app functions as intended and delivers an excellent user experience. By following the practices outlined in this comprehensive guide and using the provided code samples, you can build a solid testing strategy for your Flutter mobile apps.

Remember to invest time in writing unit tests, widget tests, and integration tests, and consider adopting test-driven development practices. Furthermore, integrating your testing efforts with a reliable CI/CD pipeline will help you maintain a high level of quality and efficiency throughout the development lifecycle.

Last but not the least, use tools like Firebase, Instabug, BugSnag and Appxiom to detect performance issues and bugs.

Happy testing!