Performance and reliability cheat sheet

Revise Android performance and reliability: LeakCanary, ANR fixes, Baseline Profiles, JankStats, WorkManager, R8, and crash reporting.

Key ideas

  1. LeakCanary must be debugImplementation only; heap dumps freeze the app and write large files, so it must never ship in release.
  2. Input dispatch ANR timeout is 5 seconds; BroadcastReceiver and service timeouts differ by priority and Android version.
  3. Cold start is the slowest start type; optimise it first. TTID is automatic, TTFD needs reportFullyDrawn() when real content is visible.
  4. Frame budget is 1000 ms divided by refresh rate; use JankStats and Perfetto on mid-range devices, not just flagships.
  5. PeriodicWorkRequestBuilder enforces a 15-minute minimum; WorkManager manages wake locks and respects Doze and App Standby.
  6. R8 full mode is the default since AGP 8.0; use the narrowest keep rule and keep mapping.txt per release for crash deobfuscation.
  7. Null the Fragment view binding in onDestroyView(); collect Flows with viewLifecycleOwner.lifecycleScope and repeatOnLifecycle.
  8. A synchronized block shared between main and background threads is a hidden ANR cause; prefer Mutex.withLock which suspends.
  9. A retained object is not a confirmed leak; LeakCanary dumps after 5 retained objects while visible, or 1 when the app is backgrounded.
  10. Thread.setDefaultUncaughtExceptionHandler must chain to the previous handler; never call Process.killProcess or System.exit inside it.

APIs at a glance

API or termUse it for
LeakCanary / AppWatcher.objectWatcherdetect memory leaks in debug builds; call expectWeaklyReachable for custom objects
viewLifecycleOwner.lifecycleScope + repeatOnLifecyclecollect Flows tied to the view lifecycle so collection stops in onStop
BaselineProfileRule.collect()generate Baseline Profiles in a macrobenchmark test module
JankStats.createAndTrack()track janky frames with UI state via PerformanceMetricsState
PeriodicWorkRequestBuilderschedule periodic background work with a 15-minute minimum interval
StrictMode.ThreadPolicydetect main-thread disk I/O and network in debug builds
ApplicationExitInforead crash and ANR reasons and traces from API 30+
Thread.setDefaultUncaughtExceptionHandlerinstall a process-wide crash handler that chains to the previous one
reportFullyDrawn() / ReportDrawnWhenreport TTFD when the first real content is visible, not at the end of onCreate
R8 / proguard-android-optimize.txtshrink, optimise, and obfuscate release builds; use narrowest keep rules
androidx.tracing.trace()add named Perfetto slices with near-zero overhead when tracing is inactive
OkHttpClient with Cacheone shared client per app for connection pooling and HTTP caching

Snippets

Null Fragment binding in onDestroyView

class ChatFragment : Fragment(R.layout.fragment_chat) {
    private var _binding: FragmentChatBinding? = null // generated by view binding
    private val binding get() = _binding!!
 
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentChatBinding.bind(view)
    }
 
    override fun onDestroyView() {
        super.onDestroyView()
        binding.chatList.adapter = null
        _binding = null
    }
}

Move I/O and parsing off the main thread

@Serializable
data class Item(val id: String, val title: String)
 
fun Fragment.loadItems(file: File, adapter: ListAdapter<Item, *>) {
    viewLifecycleOwner.lifecycleScope.launch {
        val raw = withContext(Dispatchers.IO) { file.readText() }
        val items = withContext(Dispatchers.Default) {
            Json.decodeFromString<List<Item>>(raw)
        }
        adapter.submitList(items)
    }
}

Chain the uncaught exception handler

fun installCrashHandler() {
    val crashlytics = FirebaseCrashlytics.getInstance()
    val previous = Thread.getDefaultUncaughtExceptionHandler()
    Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
        try {
            crashlytics.setCustomKey("crash_thread", thread.name)
        } finally {
            previous?.uncaughtException(thread, throwable)
        }
    }
}

Generate a Baseline Profile

@RunWith(AndroidJUnit4::class)
class BaselineProfileGenerator {
    @get:Rule val rule = BaselineProfileRule()
    @Test
    fun generate() = rule.collect(
        packageName = "com.example.app",
        includeInStartupProfile = true
    ) {
        pressHome(); startActivityAndWait()
    }
}

Rules of thumb

  • Prefer viewLifecycleOwner.lifecycleScope with repeatOnLifecycle over GlobalScope or the Fragment's own lifecycleScope for UI-bound Flow collection.
  • Never add LeakCanary to a release build; use debugImplementation and rely on lint, code review, and instrumented tests in release.
  • Prefer Mutex.withLock over synchronized when a lock is shared between the main thread and a background thread.
  • Never call Process.killProcess or System.exit inside an uncaught exception handler; always chain to the previous handler.
  • Prefer PeriodicWorkRequestBuilder with enqueueUniquePeriodicWork over exact alarms for periodic sync; exact alarms need SCHEDULE_EXACT_ALARM on Android 12+.
  • Never hold a wake lock without a timeout; prefer WorkManager, which acquires and releases the lock for you.

Gotchas

  • Forgetting to null _binding in onDestroyView. The Fragment on the back stack keeps the entire View tree alive until it is destroyed, causing a memory leak. Fix: set _binding = null in onDestroyView() and null the adapter reference too.
  • Calling reportFullyDrawn() at the end of onCreate. The screen usually shows a loading state, so TTFD equals TTID and hides data-loading time. Fix: call it when the first real content is visible, e.g. ReportDrawnWhen { !state.isLoading }.
  • Storing an Activity, View, or Context in a Kotlin object or companion object. Static references live as long as the process, creating a leak that Lint flags as StaticFieldLeak. Fix: use applicationContext for long-lived holders or pass data as parameters.
  • Using synchronized between the main thread and a background thread. The main thread blocks while the background thread holds the lock during slow I/O, and the 5-second input timer runs out. Fix: use Mutex.withLock, which suspends instead of blocking.
  • Creating a new OkHttpClient per request. Each client has its own connection pool and cache, so you pay a new handshake and lose caching every time. Fix: create one shared client, e.g. via a Hilt @Singleton provider.
  • Disabling R8 full mode to hide a release-only crash. android.enableR8.fullMode=false masks the missing keep rule instead of fixing it. Fix: use -printusage or the stack trace to find the class and add a targeted rule.

Quick interview answers

What is the input dispatch ANR timeout and what are the main causes?

The input dispatch ANR timeout is 5 seconds; it fires when the app has not handled a touch or key event within that window. The main causes are main-thread I/O, lock contention or deadlock, heavy CPU work, and slow binder calls.

How do you collect a Flow into a Fragment UI without leaking?

Use viewLifecycleOwner.lifecycleScope.launch with viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED). This cancels collection when the view is destroyed, unlike the Fragment's own lifecycleScope, which survives view destruction while the Fragment is on the back stack.

How do you generate and verify a Baseline Profile?

Generate it with BaselineProfileRule.collect() in a macrobenchmark module, run via the Baseline Profile Gradle plugin. Verify by comparing CompilationMode.None() with CompilationMode.Partial(BaselineProfileMode.Require) in Macrobenchmark, or check ProfileVerifier at runtime.

What must you do in a custom uncaught exception handler?

Save the previous handler with Thread.getDefaultUncaughtExceptionHandler() and call it at the end of your handler inside a finally block. Do not call Process.killProcess or System.exit, and do not call recordException for the fatal crash because Crashlytics already records it.

How do you handle periodic background work efficiently on Android?

Use PeriodicWorkRequestBuilder with a 15-minute minimum interval and enqueueUniquePeriodicWork with ExistingPeriodicWorkPolicy.KEEP to avoid duplicates. Let WorkManager manage wake locks and respect Doze and App Standby instead of using exact alarms, which need SCHEDULE_EXACT_ALARM on Android 12+.

Why must you keep the R8 mapping file per release?

mapping.txt changes with every build and is the only way to deobfuscate crash traces from that build. Without it, crash reports stay unreadable; let the Crashlytics Gradle plugin upload it and archive it in CI.

Go deeper