App startup and baseline profiles

Learn Android app startup: cold, warm and hot starts, TTID and TTFD with reportFullyDrawn, App Startup, and Baseline Profiles generated with Macrobenchmark. About 25 minutes.

Why it matters

  • Startup is the first performance users notice. Android vitals in Play Console tracks slow cold, warm and hot starts, and Macrobenchmark lets you measure the same thing before release.
  • Baseline Profiles tell Android Runtime (ART) which code to compile ahead of time, so the startup path and key journeys avoid interpretation and just-in-time (JIT) compilation from the first launch after install.
  • Senior interviews ask you to explain TTID versus TTFD, where reportFullyDrawn() belongs, and how you generate, ship and verify a Baseline Profile.
  • Startup work in Application.onCreate and content providers delays every cold start, and slow startup can also cause broadcast and service ANRs (see the ANR lesson).

The simple explanation

  • Cold start is opening a closed restaurant: unlock, switch on the lights, heat the stove, then cook the first dish.
  • Warm start: the restaurant is open but the table was cleared, so you only reset that table.
  • Hot start: the diner never left; you just bring the menu back.
  • TTID is when the first plate hits the table (even if it is only bread); TTFD is when the full meal is served.
  • A Baseline Profile is prep work done before opening: the chef has the most-ordered dishes ready, so the first customers are not slow.

How do you measure and improve Android app startup? Measure two metrics. Time to initial display (TTID) is the time until the first frame is drawn; the system reports it automatically as the Displayed line in Logcat. Time to full display (TTFD) is the time until the screen shows its real content; you report it by calling ComponentActivity.reportFullyDrawn() once that content is visible. Then cut startup work and add a Baseline Profile.

Android defines three start types:

Start typeProcessWhat runs
ColdCreated from scratchProcess creation, Application.onCreate, Activity creation, layout or composition, first frame
WarmUsually alive, but the Activity must be recreated (or the process was killed and the saved state is restored)Activity.onCreate with saved state, layout, first frame
HotAlive, Activity still in memoryonStart and onResume; the existing UI is brought to the front

Baseline Profiles are lists of classes and methods (rules in a baseline-prof.txt file) that ART compiles ahead of time. Without one, app code is interpreted and JIT-compiled in memory, or compiled in the background when the device is idle. With one, Google Play ships the profile with the APK and ART compiles those methods during installation. For installs outside Play (for example sideloading or local testing), the androidx.profileinstaller library installs the profile on first run. The compiled profile ends up in the app as assets/dexopt/baseline.prof.

You generate a profile with the Baseline Profile Gradle plugin (androidx.baselineprofile) and a Macrobenchmark test that uses BaselineProfileRule to drive the app through startup and key journeys. The plugin runs the test on a device, then writes the rules into your app module (under src/<variant>/generated/baselineProfiles/). Startup Profiles are a related build-time input: rules collected with includeInStartupProfile = true let R8 place startup code in the primary DEX file.

The App Startup library (androidx.startup) replaces one ContentProvider per library with a single shared InitializationProvider. Each Initializer<T> lists its dependencies, and the library runs them in dependency order before Application.onCreate, or lazily when you call AppInitializer yourself.

Notes

  • Cold start creates the process; warm start recreates the Activity (often in a live process); hot start brings an existing Activity back with onStart and onResume. Cold start is the slowest and the one to optimise first.
  • TTID is reported automatically (the Displayed line in Logcat). TTFD needs reportFullyDrawn(), called once the first screen shows its real content.
  • Calling reportFullyDrawn() too early (for example at the end of onCreate) makes TTFD look the same as TTID and hides the time spent loading data.
  • In Compose, use ReportDrawnWhen { condition } or ReportDrawnAfter { } from androidx.activity.compose; in Views, call reportFullyDrawn() or use fullyDrawnReporter when several parts must finish.
  • Baseline Profiles are generated with BaselineProfileRule.collect() in a Macrobenchmark-style test module, run by the Baseline Profile Gradle plugin (./gradlew :app:generateBaselineProfile). StartupTimingMetric with MacrobenchmarkRule measures startup; it does not generate the profile.
  • Play installs use the profile shipped with the APK. profileinstaller installs it on first run for installs that do not go through Play; Android Studio's Baseline Profile template adds it for you.
  • Generate profiles against a non-obfuscated build; the plugin uses a special non-minified variant for this, and the build rewrites the rules to match the R8 output of your release build. Regenerate when the code on your critical paths changes.
  • Verify a profile with Macrobenchmark by comparing CompilationMode.None() with CompilationMode.Partial(BaselineProfileMode.Require), or check its status at runtime with ProfileVerifier from profileinstaller.
  • App Startup Initializer.create() runs on the main thread during startup. Keep it cheap; anything slow should be lazy or moved to a background thread or WorkManager.
  • To make an Initializer lazy, remove its meta-data entry from the manifest (with tools:node="remove") and call AppInitializer.getInstance(context).initializeComponent(MyInitializer::class.java) when you need it.

Code example

This shows the three pieces: an App Startup Initializer, reporting TTFD from Compose once real content is shown, and the Macrobenchmark tests that generate a Baseline Profile and measure startup with it.

// --- App Startup Initializer (app module) ---
class LoggerInitializer : Initializer<Logger> {
    override fun create(context: Context): Logger =
        Logger.init(context.applicationContext) // must be fast: runs on the main thread
 
    override fun dependencies(): List<Class<out Initializer<*>>> = emptyList()
}
 
// AndroidManifest.xml:
// <provider android:name="androidx.startup.InitializationProvider"
//     android:authorities="${applicationId}.androidx-startup"
//     android:exported="false" tools:node="merge">
//     <meta-data android:name="com.example.LoggerInitializer"
//         android:value="androidx.startup" />
// </provider>
 
// --- Report TTFD when the first real content is visible ---
class MainActivity : ComponentActivity() {
    private val viewModel: HomeViewModel by viewModels()
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val state by viewModel.uiState.collectAsStateWithLifecycle()
            HomeScreen(state)
            // Calls reportFullyDrawn() once loading has finished
            ReportDrawnWhen { !state.isLoading }
        }
    }
}
 
// --- Baseline Profile generator (":baselineprofile" test module) ---
@RunWith(AndroidJUnit4::class)
class BaselineProfileGenerator {
    @get:Rule
    val rule = BaselineProfileRule()
 
    @Test
    fun generate() = rule.collect(
        packageName = "com.example.app",
        includeInStartupProfile = true // also feeds the Startup Profile
    ) {
        pressHome()
        startActivityAndWait()
        // Exercise key journeys here, for example scrolling the home feed
    }
}
 
// --- Startup benchmark (same module) ---
@RunWith(AndroidJUnit4::class)
class StartupBenchmark {
    @get:Rule
    val rule = MacrobenchmarkRule()
 
    @Test
    fun coldStartWithProfile() = rule.measureRepeated(
        packageName = "com.example.app",
        metrics = listOf(StartupTimingMetric()), // reports TTID, and TTFD if reported
        iterations = 10,
        startupMode = StartupMode.COLD,
        compilationMode = CompilationMode.Partial(BaselineProfileMode.Require)
    ) {
        pressHome()
        startActivityAndWait()
    }
}
  • LoggerInitializer is discovered through the merged InitializationProvider entry and runs before Application.onCreate.
  • ReportDrawnWhen reports TTFD only after the loading state ends, so the metric includes the time to load the home data.
  • BaselineProfileRule.collect() records which code runs during the block; the Gradle plugin copies the result into the app. The benchmark then compares cold starts with the profile required; run a second variant with CompilationMode.None() to see the difference.

Run the idea in plain Kotlin

data class Event(val atMs: Int, val name: String)

fun main() {
  // Illustrative cold-start timeline for one launch (made-up numbers)
  val events = listOf(
      Event(0, "Launch intent received"),
      Event(180, "Process started, Application.onCreate done"),
      Event(320, "MainActivity.onCreate done"),
      Event(410, "First frame drawn (loading UI)"),
      Event(900, "Home data shown, reportFullyDrawn()")
  )
  for (e in events) {
      println(e.atMs.toString().padStart(4) + " ms  " + e.name)
  }
  val ttid = events.first { it.name.startsWith("First frame") }.atMs
  val ttfd = events.first { it.name.contains("reportFullyDrawn") }.atMs
  println("TTID = " + ttid + " ms")
  println("TTFD = " + ttfd + " ms")
  println("")

  // App Startup idea: run each initializer after its dependencies
  val deps = mapOf(
      "Logger" to listOf<String>(),
      "Database" to listOf("Logger"),
      "Analytics" to listOf("Logger", "Database")
  )
  val done = mutableListOf<String>()
  fun init(name: String) {
      if (name in done) return
      for (d in deps.getValue(name)) init(d)
      done.add(name)
      println("Initialized " + name)
  }
  init("Analytics")
}

Expected output:

   0 ms  Launch intent received
 180 ms  Process started, Application.onCreate done
 320 ms  MainActivity.onCreate done
 410 ms  First frame drawn (loading UI)
 900 ms  Home data shown, reportFullyDrawn()
TTID = 410 ms
TTFD = 900 ms

Initialized Logger
Initialized Database
Initialized Analytics

In production

Slow first frame after a release that loaded config in onCreate
  • Android vitals showed more slow cold starts after a release, and users on mid-range devices saw a blank window before the home screen.
  • A Perfetto trace of a cold start showed the main thread blocked inside runBlocking { configRepository.load() } in MainActivity.onCreate, waiting for a database read and a config file parse before the first frame.
  • reportFullyDrawn() was called at the end of onCreate, so TTFD equalled TTID and dashboards never showed how long users waited for real content.
The fix
  • Removed runBlocking; the ViewModel loads the config in viewModelScope and the screen shows a lightweight loading state immediately.
  • Replaced the early reportFullyDrawn() with ReportDrawnWhen { !state.isLoading }, so TTFD now reflects when content appears.
  • Added a StartupTimingMetric Macrobenchmark run on a dedicated test device for each release candidate, and regenerated the Baseline Profile so the new startup path is covered.
Startup ANRs after adding several SDK initialisers
  • ApplicationExitInfo records collected on the next launch showed REASON_ANR exits during startup after a release added three SDKs.
  • Each SDK registered its own ContentProvider that initialised on the main thread before Application.onCreate, and one of them opened and migrated a database there.
  • On low-end devices this pushed startup past the broadcast timeout for the app's push-notification receiver, and users who tapped during the freeze hit the input timeout.
The fix
  • Moved the app's own setup to App Startup Initializers, removed the SDK providers that supported it with tools:node="remove", and initialised those SDKs lazily or after the first frame.
  • Moved the database migration off the main thread; it now runs on the first database access from a background dispatcher.
  • Added a cold-start Macrobenchmark that clears app data in its setup block (pm clear) to cover first launch after install.

Common mistakes

  • Calling reportFullyDrawn() at the end of onCreate. At that point the screen usually shows a loading state, so TTFD equals TTID and hides the data-loading time. Report it when the real content is visible.
  • Using StartupTimingMetric to generate a Baseline Profile. StartupTimingMetric with MacrobenchmarkRule measures startup. Profiles are generated with BaselineProfileRule.collect(), usually through the Baseline Profile Gradle plugin.
  • Never verifying the profile. A profile that does not cover your real startup path gives little benefit. Compare CompilationMode.None() against CompilationMode.Partial(BaselineProfileMode.Require) in Macrobenchmark, or check ProfileVerifier at runtime.
  • Doing heavy work in Application.onCreate or an Initializer. Both run on the main thread before the first Activity on every cold start. Defer non-essential setup, make it lazy, or move it to a background thread or WorkManager.
  • Letting the profile go stale. When the startup path or key journeys change, regenerate the profile, ideally as part of the release process, so new code is covered.
  • Keeping one ContentProvider per library for initialisation. Each provider adds startup cost and their order is hard to control. App Startup uses one provider with explicit dependencies and lets you make initialisers lazy.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“Explain the difference between cold, warm, and hot start in Android.”

“What is a Baseline Profile and how do you generate and ship one?”

“What are TTID and TTFD, and when should you call reportFullyDrawn()?”

“How does the App Startup library work and what are its constraints?”

Quiz

Which start type includes creating the process and running Application.onCreate?

What does calling reportFullyDrawn() measure?

Which API records the classes and methods for a Baseline Profile?

What is the main constraint of an androidx.startup Initializer?

0 of 4 answered

Mini task

Add and verify a Baseline Profile (15 min)

  1. In Android Studio, add a module with the Baseline Profile Generator template (File, New, New Module). It creates a test module with the androidx.baselineprofile plugin and a BaselineProfileGenerator test, applies the plugin to your app module, adds the baselineProfile(project(":baselineprofile")) dependency, and adds profileinstaller. Use the current stable versions it suggests.
  2. Open the generated test and make sure the collect block starts your app with startActivityAndWait() and runs one key journey, such as scrolling your main list. Keep includeInStartupProfile = true for the startup journey.
  3. With a device or emulator connected (on Android 13 or higher no root is needed), run ./gradlew :app:generateBaselineProfile.
  4. Open app/src/release/generated/baselineProfiles/ (the folder name follows your variant) and look at baseline-prof.txt. Find a few of your own classes in it.
  5. Add a startup benchmark like the one in the example, with one test using CompilationMode.None() and one using CompilationMode.Partial(BaselineProfileMode.Require). Run both and compare timeToInitialDisplayMs.

Done condition: the generated baseline-prof.txt contains rules for your app's classes, and the cold-start benchmark with the profile required reports a lower median timeToInitialDisplayMs than the run with CompilationMode.None().

Next: Jank, frames and Perfetto