App fundamentals cheat sheet

Revise Android app fundamentals: Activity lifecycle, configuration changes, Fragments, Intents, runtime permissions, Context, and task management.

Key ideas

  1. A configuration change (rotation, dark mode, folding, language, font size, window resize) destroys and recreates the Activity by default; a ViewModel survives but remember does not.
  2. onDestroy is not guaranteed; when the system kills the process no callback runs, so release resources in onStop or onPause.
  3. registerForActivityResult must be called before the owner reaches STARTED; calling it in onStart or onResume throws IllegalStateException.
  4. In Compose, rememberSaveable survives configuration changes and process death; remember is lost on a configuration change.
  5. When targeting API 31+, every component with an intent filter must declare android:exported, and every PendingIntent needs FLAG_IMMUTABLE or FLAG_MUTABLE.
  6. Fragment.context is nullable before onAttach and after onDetach; use requireContext() only while attached and never store it in a long-lived object.
  7. singleTop reuses an instance only when it is on top; singleTask keeps one instance and finishes every Activity above it in the task.
  8. Dangerous permissions must be requested at the point of use; never cache "granted" because users can revoke in Settings and Android 11+ auto-resets unused apps.
  9. Collect Flows with collectAsStateWithLifecycle() in Compose and repeatOnLifecycle(STARTED) in Fragments so collection stops when the screen is not visible.
  10. Since Android 12, pressing Back on the root launcher Activity moves the app to the background; it does not finish the Activity.

APIs at a glance

API or termUse it for
onSaveInstanceStateSave small UI state (ids, short text) before the Activity is destroyed on a configuration change; runs after onStop on API 28+.
rememberSaveableCompose state that survives both a configuration change and process death; use for user input like text fields.
collectAsStateWithLifecycle()Collect a Flow in Compose so the collection stops automatically when the screen is not visible.
registerForActivityResultRegister a permission or Activity-result launcher as a field or in onCreate, before the owner is STARTED.
android:exportedRequired manifest attribute (API 31+) on every <activity>, <service>, <receiver> that has an intent filter; build fails without it.
FLAG_IMMUTABLE / FLAG_MUTABLERequired mutability flag on every PendingIntent when targeting API 31+; use FLAG_IMMUTABLE unless an inline reply or bubble must fill the intent.
OnBackPressedDispatcher.addCallback()Replace the deprecated onBackPressed() for custom back handling; use BackHandler in Compose.
SavedStateHandleStore screen state inside a ViewModel so it survives rotation and process death; pair with getStateFlow.
repeatOnLifecycle(STARTED)Collect a Flow inside a Fragment so the collection stops when the view is not visible; use with viewLifecycleOwner.
FLAG_ACTIVITY_CLEAR_TOP + FLAG_ACTIVITY_SINGLE_TOPReuse an existing Activity instance and deliver the new intent to onNewIntent instead of finishing and recreating it.
@ApplicationContextHilt qualifier for injecting the Application Context into singletons and ViewModels; @ActivityContext must not be used there.
shouldShowRequestPermissionRationaleCheck whether a denied permission can still be requested; returns false when never asked, granted, or permanently denied.

Snippets

ViewModel with SavedStateHandle for screen state

data class Item(val id: Long, val title: String)
interface SearchRepository { suspend fun search(query: String): List<Item> }
 
@HiltViewModel
class SearchViewModel @Inject constructor(
    private val savedStateHandle: SavedStateHandle,
    private val repository: SearchRepository,
) : ViewModel() {
    val query: StateFlow<String> = savedStateHandle.getStateFlow("query", "")
    val results: StateFlow<List<Item>> = query
        .mapLatest { repository.search(it) }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
    fun onQueryChange(text: String) { savedStateHandle["query"] = text }
}

Fragment: bind, collect, and release with viewLifecycleOwner

// Inside a Fragment(R.layout.fragment_profile) with a viewModel and a render(state) function
private var _binding: FragmentProfileBinding? = null
 
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    _binding = FragmentProfileBinding.bind(view)
    viewLifecycleOwner.lifecycleScope.launch {
        viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.state.collect { render(it) }
        }
    }
}
 
override fun onDestroyView() {
    _binding = null
    super.onDestroyView()
}

Runtime permission request with registerForActivityResult

// Inside a ComponentActivity that defines openCamera() and handleCameraDenied()
private val cameraLauncher =
    registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        if (granted) openCamera() else handleCameraDenied()
    }
 
private fun requestCamera() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
        == PackageManager.PERMISSION_GRANTED) { openCamera(); return }
    cameraLauncher.launch(Manifest.permission.CAMERA)
}

Task flags: reuse an instance and wipe a task

// Reuse existing instance; finish everything above it
val intent = Intent(this, DetailActivity::class.java).addFlags(
    Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
)
startActivity(intent)
 
// Logout: wipe the task, make LoginActivity the only screen
val logout = Intent(this, LoginActivity::class.java).addFlags(
    Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
)
startActivity(logout)

Rules of thumb

  • Prefer rememberSaveable or SavedStateHandle over remember for any user input that must survive rotation.
  • Never pass an Activity or View reference into a ViewModel or singleton; inject a repository or use @ApplicationContext instead.
  • Never call registerForActivityResult after the owner is STARTED; declare it as a field initializer or in onCreate.
  • Prefer collectAsStateWithLifecycle() in Compose and repeatOnLifecycle(STARTED) in Fragments so collection stops when the screen is hidden.
  • Never cache a permission as "granted"; call checkSelfPermission every time before using the feature because users can revoke and Android 11+ auto-resets.
  • Prefer OnBackPressedDispatcher.addCallback() or BackHandler over the deprecated onBackPressed(); once predictive back is enabled the old method is not called.

Gotchas

  • Using remember for user input in Compose. The value is lost on a configuration change such as rotation, so the user sees an empty field. Use rememberSaveable or store the value in a ViewModel with SavedStateHandle.
  • Observing LiveData or collecting a Flow with this in a Fragment. Each return from the back stack adds another observer to a Fragment that never died, causing duplicate work and memory growth. Use viewLifecycleOwner so the observer is removed with the view.
  • Omitting android:exported on a component that has an intent filter. When targeting API 31+ the manifest merger fails the build. Set true for launcher and deep-link activities, false for everything else.
  • Starting an Activity from a Service or BroadcastReceiver without FLAG_ACTIVITY_NEW_TASK. The system throws AndroidRuntimeException because the caller is not in a task. Even with the flag, Android 10+ usually blocks background starts; post a notification with a PendingIntent instead.
  • Releasing resources only in onDestroy. onDestroy is not guaranteed; the system can kill the process without calling it. Release the camera, sensors, and receivers in onStop or onPause.
  • Passing this (the Activity) into a ViewModel constructor. The ViewModel outlives the Activity across a configuration change and keeps the destroyed Activity and its view tree in memory, causing a leak. Inject a repository or use @ApplicationContext.

Quick interview answers

What happens to an Activity when the user rotates the device?

By default the system destroys the current Activity and creates a new one, calling onSaveInstanceState after onStop on API 28+. A ViewModel survives the recreation, but remember in Compose does not; use rememberSaveable or SavedStateHandle for state that must persist.

Why must registerForActivityResult be called before the owner is STARTED?

The launcher is tied to the lifecycle owner's state, and calling it after STARTED (for example in onStart or onResume) throws IllegalStateException. Declare the launcher as a field initializer or inside onCreate so it is registered in time.

What is the difference between singleTop and singleTask launch modes?

singleTop reuses the existing instance only when it is already on top of the task and calls onNewIntent; if it is lower in the stack a new instance is created. singleTask keeps at most one instance and finishes every Activity above it in its task when reused.

How do you handle a permanently denied runtime permission?

There is no direct API; the reliable check is in the result callback: the permission was denied and shouldShowRequestPermissionRationale now returns false. In that state launch() shows no dialog and the callback receives false at once, so show a dialog that opens Settings.ACTION_APPLICATION_DETAILS_SETTINGS.

Why should a ViewModel not hold a Context or an Activity reference?

A ViewModel survives configuration changes, so it keeps the old destroyed Activity and its view tree in memory, causing a leak. Inject a repository instead, or use AndroidViewModel / @ApplicationContext if the Application Context is truly needed.

What does FLAG_ACTIVITY_CLEAR_TOP do to a standard Activity, and how do you keep the instance?

CLEAR_TOP alone finishes and recreates a standard target, losing its in-memory state. Add FLAG_ACTIVITY_SINGLE_TOP so the existing instance is reused and the new intent is delivered to onNewIntent instead.

Go deeper