Bird
Raised Fist0
Android Kotlinmobile~20 mins

Lifecycle awareness in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Lifecycle Demo Screen
This screen shows how to observe Android lifecycle events and display them in a list.
Target UI
-------------------------
| Lifecycle Demo Screen  |
-------------------------
| Events:               |
| - onCreate            |
| - onStart             |
| - onResume            |
|                       |
| [Clear Events Button] |
-------------------------
Display a list of lifecycle events as they happen.
Observe lifecycle events: onCreate, onStart, onResume, onPause, onStop, onDestroy.
Add each event name to the list when it occurs.
Add a button to clear the list of events.
Use AndroidX Lifecycle components for observing lifecycle.
UI should update automatically when events are added or cleared.
Starter Code
Android Kotlin
package com.example.lifecycleawareness

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            LifecycleDemoScreen()
        }
    }
}

@Composable
fun LifecycleDemoScreen() {
    // TODO: Implement lifecycle event list and observer
    // TODO: Display events in a LazyColumn
    // TODO: Add a button to clear events
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Android Kotlin
package com.example.lifecycleawareness

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.Modifier
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            LifecycleDemoScreen(lifecycle = lifecycle)
        }
    }
}

@Composable
fun LifecycleDemoScreen(lifecycle: Lifecycle) {
    val events = remember { mutableStateListOf<String>() }

    DisposableEffect(lifecycle) {
        val observer = LifecycleEventObserver { _, event ->
            when(event) {
                Lifecycle.Event.ON_CREATE -> events.add("onCreate")
                Lifecycle.Event.ON_START -> events.add("onStart")
                Lifecycle.Event.ON_RESUME -> events.add("onResume")
                Lifecycle.Event.ON_PAUSE -> events.add("onPause")
                Lifecycle.Event.ON_STOP -> events.add("onStop")
                Lifecycle.Event.ON_DESTROY -> events.add("onDestroy")
                else -> {}
            }
        }
        lifecycle.addObserver(observer)

        onDispose {
            lifecycle.removeObserver(observer)
        }
    }

    Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
        Column {
            LazyColumn(modifier = Modifier.weight(1f)) {
                items(events) { event ->
                    Text(text = "- $event")
                }
            }
            Button(onClick = { events.clear() }) {
                Text(text = "Clear Events")
            }
        }
    }
}

This solution uses Jetpack Compose to build the UI and AndroidX Lifecycle components to observe lifecycle events.

We create a mutableStateListOf to hold event names so the UI updates automatically when the list changes.

The LifecycleEventObserver listens to lifecycle changes and adds the event name to the list.

We use DisposableEffect to add the observer when the composable enters composition and remove it when it leaves, avoiding leaks.

The UI shows the events in a scrollable list and a button to clear the list.

Final Result
Completed Screen
-------------------------
| Lifecycle Demo Screen  |
-------------------------
| Events:               |
| - onCreate            |
| - onStart             |
| - onResume            |
|                       |
| [Clear Events Button] |
-------------------------
When the screen starts, lifecycle events like onCreate, onStart, onResume appear in the list.
If the app is backgrounded and resumed, onPause, onStop, onStart, onResume events appear accordingly.
Tapping 'Clear Events' empties the list.
Stretch Goal
Add a Text showing the total count of lifecycle events recorded.
💡 Hint
Use events.size to get the count and display it above the list.

Practice

(1/5)
1. What is the main purpose of lifecycle awareness in an Android app?
easy
A. To add animations to UI components
B. To change the app's theme colors dynamically
C. To increase the app's download speed
D. To respond to app state changes like start and stop

Solution

  1. Step 1: Understand lifecycle awareness concept

    Lifecycle awareness means the app knows when it starts, stops, or pauses.
  2. Step 2: Identify the main goal

    The goal is to respond properly to these state changes to save resources and improve user experience.
  3. Final Answer:

    To respond to app state changes like start and stop -> Option D
  4. Quick Check:

    Lifecycle awareness = respond to state changes [OK]
Hint: Lifecycle awareness means reacting to app start/stop events [OK]
Common Mistakes:
  • Confusing lifecycle with UI styling
  • Thinking it controls app download speed
  • Assuming it only adds animations
2. Which annotation is used to mark a method that listens to lifecycle events in Android Kotlin?
easy
A. @OnClick
B. @OnLifecycleEvent
C. @Override
D. @Subscribe

Solution

  1. Step 1: Recall lifecycle event annotations

    In Android Kotlin, @OnLifecycleEvent marks methods that respond to lifecycle changes.
  2. Step 2: Compare options

    @OnClick is for button clicks, @Override is for overriding methods, @Subscribe is for event bus patterns.
  3. Final Answer:

    @OnLifecycleEvent -> Option B
  4. Quick Check:

    Lifecycle event listener annotation = @OnLifecycleEvent [OK]
Hint: Use @OnLifecycleEvent to handle lifecycle changes [OK]
Common Mistakes:
  • Using @OnClick for lifecycle events
  • Confusing @Override with lifecycle annotations
  • Thinking @Subscribe is for lifecycle
3. Given this code snippet, what lifecycle event will trigger the onStartEvent() method?
class MyObserver : LifecycleObserver {
  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  fun onStartEvent() {
    println("Started")
  }
}
medium
A. When the app starts or comes to foreground
B. When the app is paused
C. When the app is stopped
D. When the app is destroyed

Solution

  1. Step 1: Identify the lifecycle event annotation

    The method is annotated with @OnLifecycleEvent(Lifecycle.Event.ON_START), which means it triggers on start.
  2. Step 2: Understand ON_START meaning

    ON_START happens when the app moves to the foreground or becomes visible.
  3. Final Answer:

    When the app starts or comes to foreground -> Option A
  4. Quick Check:

    ON_START event triggers on app foreground [OK]
Hint: ON_START means app is visible or foregrounded [OK]
Common Mistakes:
  • Confusing ON_START with ON_PAUSE or ON_STOP
  • Thinking ON_START means app destroyed
  • Assuming it triggers on app pause
4. What is wrong with this observer class?
class MyObserver : LifecycleObserver {
  fun onResumeEvent() {
    println("Resumed")
  }
}
medium
A. Missing @OnLifecycleEvent annotation on the method
B. Class should extend Activity instead of LifecycleObserver
C. Method name must be onStartEvent instead of onResumeEvent
D. println cannot be used inside lifecycle methods

Solution

  1. Step 1: Check method annotation

    The method onResumeEvent lacks the @OnLifecycleEvent annotation, so it won't be called on lifecycle changes.
  2. Step 2: Verify class and method correctness

    The class correctly implements LifecycleObserver, method name can be any valid name, and println is allowed.
  3. Final Answer:

    Missing @OnLifecycleEvent annotation on the method -> Option A
  4. Quick Check:

    Lifecycle methods need @OnLifecycleEvent annotation [OK]
Hint: Always add @OnLifecycleEvent to lifecycle methods [OK]
Common Mistakes:
  • Forgetting the annotation
  • Thinking method name must be fixed
  • Assuming println is disallowed
5. You want to save battery by stopping a sensor when the app is not visible. Which lifecycle event should you observe to stop the sensor properly?
hard
A. Lifecycle.Event.ON_CREATE
B. Lifecycle.Event.ON_RESUME
C. Lifecycle.Event.ON_PAUSE
D. Lifecycle.Event.ON_DESTROY

Solution

  1. Step 1: Understand when to stop sensors

    Sensors should stop when the app is no longer visible to save battery, which happens at ON_PAUSE.
  2. Step 2: Match lifecycle event to stopping action

    ON_PAUSE is called when the app loses focus but is not yet destroyed, ideal for stopping sensors.
  3. Final Answer:

    Lifecycle.Event.ON_PAUSE -> Option C
  4. Quick Check:

    Stop sensors on ON_PAUSE to save battery [OK]
Hint: Stop sensors on ON_PAUSE to save battery [OK]
Common Mistakes:
  • Stopping sensors too late at ON_DESTROY
  • Stopping sensors too early at ON_CREATE
  • Confusing ON_RESUME with stopping event
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard