Activity Lifecycle and Resource Management

Activity Lifecycle and Resource Management

1. What is the Activity lifecycle?

An Activity usually represents a screen in an Android application.

During its lifetime, an Activity moves through different states based on:

* Whether the screen is being created

* Whether it is visible

* Whether the user can interact with it

* Whether another screen covers it

* Whether the Activity is being destroyed

Android provides lifecycle callback methods so the Activity can react to these changes. Correctly handling these callbacks prevents crashes, resource leaks and loss of user progress.

---

2. Complete Activity lifecycle flow

Activity launched
      |
      v
  onCreate()
      |
      v
   onStart()
      |
      v
  onResume()
      |
      v
User can interact
      |
      v
   onPause()
      |
      v
   onStop()
      |
      +----------------------+
      |                      |
User returns          Activity finishes
      |                      |
      v                      v
  onRestart()           onDestroy()
      |
      v
   onStart()
      |
      v
  onResume()

---

## 3. `onCreate()`

onCreate() is called when Android creates a new Activity instance.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        // Initial UI setup
        // ViewModel setup
        // Click listeners
        // Restore saved state
    }
}

Common work

* Inflate the Activity layout

* Initialize ViewBinding

* Obtain the ViewModel

* Configure RecyclerView

* Set click listeners

* Read Intent data

* Restore saved state

Important point

`onCreate()` can run again after:

* Screen rotation

* Language change

* Theme change

* System process death

* Activity recreation

Do not assume it runs only once during the complete lifetime of the application.

---

## 4. `onStart()`

onStart() is called when the Activity becomes visible.

override fun onStart() {
    super.onStart()

    // Screen is visible
}

At this point:

* The Activity is visible

* The user might not yet be able to interact

* The Activity is moving toward the foreground

Suitable work:

* Register visibility-related listeners

* Start observing UI-related data

* Connect to lightweight components

* Prepare animations

---

## 5. `onResume()`

onResume() is called when the Activity is visible and ready for user interaction.

override fun onResume() {
    super.onResume()

    // User can interact with this screen
}

Suitable work:

* Resume camera preview

* Resume video

* Start sensor updates

* Start location updates when required

* Enable keyboard or input handling

* Register exclusive hardware resources

onStart()  = Screen is visible
onResume() = Screen is visible and interactive

---

## 6. `onPause()`

onPause() is called when the Activity starts losing focus.

override fun onPause() {
    super.onPause()

    // Pause resources that require active interaction
}

Possible situations:

* A dialog-like Activity appears

* Another Activity is opening

* The user presses Home

* The screen is locking

* Multi-window focus changes

Suitable work:

* Pause video

* Pause animations

* Release camera access when required

* Stop sensor updates

* Save small unsaved edits

Keep onPause() fast because the next Activity may not become interactive until this callback finishes.

---

## 7. `onStop()`

onStop() is called when the Activity is no longer visible.

override fun onStop() {
    super.onStop()

    // Screen is no longer visible
}

Suitable work:

* Stop expensive UI updates

* Unregister visibility-related listeners

* Stop location updates that are not needed in the background

* Release large UI resources

* Save data to a database

* Disconnect from UI-only services

onPause()
Activity may still be visible

onStop()
Activity is no longer visible

---

## 8. `onRestart()`

onRestart() is called when a stopped Activity is returning to the foreground.

override fun onRestart() {
    super.onRestart()

    // Activity is returning after onStop()
}

Flow:

onStop()
   |
User returns
   |
onRestart()
   |
onStart()
   |
onResume()

onRestart() is not called when a completely new Activity object is created.

---

## 9. `onDestroy()`

onDestroy() is called when the Activity instance is being destroyed.

override fun onDestroy() {
    super.onDestroy()

    // Final cleanup related to this Activity instance
}

Possible reasons:

* User presses Back

* finish() is called

* Configuration changes

* Android recreates the Activity

* Host task is removed

Important:

> onDestroy() is not guaranteed when Android directly kills the application process.

Never depend on it for saving critical user data.

---

10. Visibility versus interaction

Lifecycle stateVisibleInteractive
CreatedNot necessarilyNo
StartedYesNot always
ResumedYesYes
PausedPossiblyUsually no
StoppedNoNo
DestroyedNo Activity instanceNo

Example: transparent dialog

MainActivity: onResume()
        |
Dialog Activity opens
        |
MainActivity: onPause()
        |
MainActivity is still visible
but not interactive

---

11. Lifecycle-related resource management

Resources should be acquired and released using matching lifecycle callbacks.

| Start or acquire | Stop or release |
| ---------------- | --------------- |
| `onCreate()`     | `onDestroy()`   |
| `onStart()`      | `onStop()`      |
| `onResume()`     | `onPause()`     |

Camera example

override fun onResume() {
    super.onResume()
    cameraController.start()
}

override fun onPause() {
    cameraController.stop()
    super.onPause()
}

Receiver example

override fun onStart() {
    super.onStart()
    registerReceiver(networkReceiver, intentFilter)
}

override fun onStop() {
    unregisterReceiver(networkReceiver)
    super.onStop()
}

Flow collection example

lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect { state ->
            updateUi(state)
        }
    }
}

Lifecycle-aware collection starts when the Activity reaches the required state and stops when it falls below that state.

---

12. Common mistakes

### Performing heavy work in `onCreate()`
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // Bad
    Thread.sleep(3000)
    loadCompleteDatabase()
}

This delays screen startup and may cause an ANR.

Registering without unregistering

override fun onStart() {
    registerReceiver(receiver, filter)
}

// Missing unregisterReceiver()

This may cause leaks or duplicate callbacks.

### Treating `onPause()` as background state

An Activity can be paused while still visible. Use onStop() when you specifically need to know that the Activity is no longer visible.

### Depending on `onDestroy()`

Android may kill the entire process without calling it.

---

Interview answer

> Activity lifecycle callbacks inform the Activity about changes in creation, visibility and user interaction. onStart() means the Activity is visible, while onResume() means it is visible and interactive. Resources should be acquired and released using matching callback pairs, such as onStart() with onStop() or onResume() with onPause(). Critical data should not depend on onDestroy() because it is not guaranteed during process death.