App Restart, State Restoration and Global Initialization

App Restart, State Restoration and Global Initialization

1. What happens after process death?

Suppose the user is working on a screen:

Search query = "Android"
Selected tab = 2
Scroll position = 50

The user presses Home:

Activity.onPause()
        |
Activity.onStop()
        |
App enters background

Android later needs memory:

Cached process
      |
Android kills process
      |
All in-memory objects are lost

When the user opens the app again:

New Linux process created
        |
New Application object created
        |
Application.onCreate()
        |
Activity recreated
        |
Saved state restored

The application must not assume that old singleton, ViewModel or Application data is still available.

---

2. App restart flow

User opens app
      |
      v
Process created
      |
      v
Application.onCreate()
      |
      v
Activity.onCreate()
      |
      v
Activity.onStart()
      |
      v
Activity.onResume()
      |
      v
App in foreground
      |
User presses Home
      |
      v
Activity.onPause()
      |
      v
Activity.onStop()
      |
      v
App in background
      |
Android needs memory
      |
      v
Process killed
      |
User opens app again
      |
      v
New process created
      |
      v
Application.onCreate() called again

---

3. Restoring application state

Different types of data need different storage solutions.

Data typeRecommended solution
Small temporary UI statesavedInstanceState
ViewModel stateSavedStateHandle
Compose UI valuesrememberSaveable
User preferencesDataStore
Structured application dataRoom
Authentication tokenSecure persistent storage
Reliable background workWorkManager
Temporary screen dataViewModel

---

4. Example using SavedStateHandle

class SearchViewModel(
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {

    var searchQuery: String
        get() = savedStateHandle["search_query"] ?: ""
        set(value) {
            savedStateHandle["search_query"] = value
        }
}

When the process is recreated, Android may restore the saved value.

Important business data should still come from Room, DataStore or a server.

---

5. Cold, warm and hot startup

Cold start

The process does not exist.

No app process
      |
Create process
      |
Create Application
      |
Application.onCreate()
      |
Create Activity

This startup requires the most work.

---

Warm start

Some application objects or Activity state must be recreated.

Example:

* Activity was destroyed

* Process or screen needs partial recreation

* Saved state is available

Some objects need recreation
        |
Activity created again
        |
State restored

---

Hot start

The process and Activity are still present in memory.

Activity already exists
        |
onRestart()
        |
onStart()
        |
onResume()

Application.onCreate() is not called again.

---

6. What is global initialization?

Global initialization means setting up components needed across the complete application process.

Examples:

* Dependency injection

* Logging

* Analytics

* Crash reporting

* Notification channels

* Database dependency creation

* Application lifecycle observers

* Third-party SDK configuration

---

7. Global initialization example

class MyApplication :
    Application(),
    DefaultLifecycleObserver {

    override fun onCreate() {
        super.onCreate()

        initializeLogging()
        initializeCrashReporting()
        createNotificationChannels()

        ProcessLifecycleOwner
            .get()
            .lifecycle
            .addObserver(this)
    }

    override fun onStart(owner: LifecycleOwner) {
        Log.d("AppState", "Foreground")
    }

    override fun onStop(owner: LifecycleOwner) {
        Log.d("AppState", "Background")
    }

    private fun initializeLogging() {
        // Configure logging
    }

    private fun initializeCrashReporting() {
        // Configure crash-reporting SDK
    }

    private fun createNotificationChannels() {
        // Create Android notification channels
    }
}

---

8. When does global initialization run?

App process starts
      |
Application.onCreate()

Moving between foreground and background does not recreate the Application object.

Foreground -> Background
Application.onCreate() not called

Background -> Foreground
Application.onCreate() not called

After process death:

Process killed
      |
Application object lost
      |
App opened again
      |
New Application.onCreate()

Global initialization should therefore be safe to run every time a new process starts.

---

9. Keep initialization lightweight

Bad:

override fun onCreate() {
    super.onCreate()

    Thread.sleep(3000)
    downloadLargeFile()
    readCompleteDatabase()
}

Problems:

* Slow app startup

* Blank screen for longer time

* Poor user experience

* Possible ANR

* Increased cold-start time

Better:

override fun onCreate() {
    super.onCreate()

    initializeRequiredComponents()
}

Initialize only critical components immediately.

Use lazy initialization for components that are not needed during startup.

---

10. Avoid global in-memory data

Bad:

class MyApplication : Application() {
    var currentUser: User? = null
    var selectedOrderId: String? = null
}

After process death:

currentUser = null
selectedOrderId = null

Better storage:

Login information    -> Secure DataStore
User details         -> Room or repository
Selected screen data -> SavedStateHandle
Temporary cache      -> In-memory cache with reload support

An Application object can contain temporary cache data, but the application must be able to recreate that data.

---

Final interview answer

Android separates application visibility from process lifetime. When an Activity is resumed, the app normally has foreground importance. When all Activities stop, the application moves to the background, but its process may remain alive as a cached process. Android kills less-important processes first when memory is required.

After process death, all in-memory data, ViewModels, singleton objects and Application variables are lost. When the user opens the app again, Android creates a new process, creates a new Application object, calls Application.onCreate(), and recreates the Activity.

Therefore, global initialization should be lightweight, repeatable and process-safe. Important data should be stored using SavedStateHandle, DataStore, Room, files or a server instead of relying only on global memory.