The Activity Result API

Lifecycle and app components Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

This crashes with 'LifecycleOwner is attempting to register while current state is RESUMED'. What's the fix?

class AvatarActivity : ComponentActivity() {
    fun onPickClicked() {
        val picker = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            render(uri)
        }
        picker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }
}
Options
Hint 1 of 1

When must registerForActivityResult be called?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Register the launcher as a property, and only call launch() in the click handler

Correct. Launchers must be registered before the owner is started.

Why not the others?
  • B Call it inside onResume. Still too late.
  • C Use startActivityForResult. Deprecated, and doesn't fix the design.
  • D Wrap it in runOnUiThread. It's already on the main thread; timing is the problem.

30-second answer

Register a launcher with registerForActivityResult(contract) { result -> } during setup, then call launcher.launch(input) when needed. Built-in contracts cover permissions, picking media, taking pictures and starting an Activity for a result. It replaces startActivityForResult and onActivityResult, which are deprecated, and survives process death because results go to the registered callback.

Practise saying it · 30 s. No recording, just a timer

Explain the Activity Result API.

Say your answer out loud, then check which of these points you covered:

  • Register a launcher early
  • Launch later
  • Typed contracts
  • Photo picker needs no permission

Deep dive

Register unconditionally before the Activity or Fragment is started; registering later throws.

In Compose use rememberLauncherForActivityResult.

PickVisualMedia opens the system photo picker and needs no storage permission.

Write a custom ActivityResultContract for your own screens to keep input and output typed.

Common mistakes

  • Registering inside a click handler.
  • Requesting READ_MEDIA_IMAGES to let the user pick one photo.
  • Using request codes in onActivityResult in new code.

Senior take & follow-ups

Mention the photo picker; using it instead of a storage permission is a privacy point interviewers like.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why register early?

    Show hint

    So the callback can be re-attached after the Activity is recreated.

  2. What picks a photo without permissions?

    Show hint

    The photo picker via PickVisualMedia.

Suggest a fix if something here is wrong or out of date.