package com.craigvg.lichun_android.utils import android.util.Log import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ProcessLifecycleOwner import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import javax.inject.Inject import javax.inject.Singleton /** * App lifecycle observer for tracking app foreground/background state * Ported from iOS AppDelegate lifecycle handling */ @Singleton class AppLifecycleObserver @Inject constructor() : DefaultLifecycleObserver { private val _isInForeground = MutableStateFlow(false) val isInForeground: StateFlow = _isInForeground.asStateFlow() private val _appState = MutableStateFlow(AppState.INACTIVE) val appState: StateFlow = _appState.asStateFlow() private var onForegroundCallback: (() -> Unit)? = null private var onBackgroundCallback: (() -> Unit)? = null companion object { private const val TAG = "AppLifecycleObserver" } enum class AppState { INACTIVE, FOREGROUND, BACKGROUND } /** * Initialize and attach to process lifecycle */ fun initialize() { ProcessLifecycleOwner.get().lifecycle.addObserver(this) Log.d(TAG, "AppLifecycleObserver initialized") } /** * Set callback for when app comes to foreground */ fun setOnForegroundCallback(callback: () -> Unit) { onForegroundCallback = callback } /** * Set callback for when app goes to background */ fun setOnBackgroundCallback(callback: () -> Unit) { onBackgroundCallback = callback } override fun onStart(owner: LifecycleOwner) { super.onStart(owner) _isInForeground.value = true _appState.value = AppState.FOREGROUND Log.d(TAG, "App moved to foreground") onForegroundCallback?.invoke() } override fun onStop(owner: LifecycleOwner) { super.onStop(owner) _isInForeground.value = false _appState.value = AppState.BACKGROUND Log.d(TAG, "App moved to background") onBackgroundCallback?.invoke() } override fun onCreate(owner: LifecycleOwner) { super.onCreate(owner) Log.d(TAG, "App process created") } override fun onDestroy(owner: LifecycleOwner) { super.onDestroy(owner) Log.d(TAG, "App process destroyed") } override fun onResume(owner: LifecycleOwner) { super.onResume(owner) Log.d(TAG, "App resumed") } override fun onPause(owner: LifecycleOwner) { super.onPause(owner) Log.d(TAG, "App paused") } /** * Check if app is currently in foreground */ fun isAppInForeground(): Boolean = _isInForeground.value /** * Get current app state */ fun getCurrentAppState(): AppState = _appState.value /** * Remove from process lifecycle (cleanup) */ fun cleanup() { ProcessLifecycleOwner.get().lifecycle.removeObserver(this) onForegroundCallback = null onBackgroundCallback = null Log.d(TAG, "AppLifecycleObserver cleaned up") } }