Android 앱 상태 받아오기 (Foreground, Background 상태)
Search
💽

Android 앱 상태 받아오기 (Foreground, Background 상태)

생성일
2021/11/03 03:37
태그
android on Background? on Foreground?
1.
매니페스트 등록
implementation "androidx.lifecycle:lifecycle-runtime:2.2.0" implementation "androidx.lifecycle:lifecycle-extensions:2.2.0" annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.2.0"
Kotlin
복사
2. Application class에 아래 내용을 추가한다.
class MyApplication : Application() { override fun onCreate() { super.onCreate() Log.d(TAG, "onCreate") ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver()) } }
Kotlin
복사
3. class를 하나 작성한다.
class AppLifecycleObserver : LifecycleObserver { companion object { var isBackgroundState = false } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onForeground() { isBackgroundState = false } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onBackground() { isBackgroundState = true } }
Kotlin
복사
** 화면 꺼짐상태도 인지
** ON_CREATE는 한번만 불리고, ON_DESTROY는 절대 불리지 않는 등 몇몇가지 참고할 사항이 있다. 아래 페이지 참고
class AppLifecycleObserver : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onForeground() { isBackgroundState = false DLog.e(TAG, "onForeground") } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onBackground() { isBackgroundState = true DLog.e(TAG, "onBackground") } companion object { val TAG: String = AppLifecycleObserver::class.java.simpleName private var isBackgroundState = false fun getBackgroundState(): Boolean { return isBackgroundState } } }
Kotlin
복사