본문 바로가기
Development/Android

Android - ProcessLifecycleOwner 로 앱의 Foreground/Background 상태 처리하기

by du.it.ddu 2023. 6. 19.
반응형

간혹, 앱이 Foreground인지 Background 상태인지에 따라 처리를 해 주어야할 때가 있다.

이를테면 Background에 빠졌을 때 UI와 관련된 작업을 멈춘다던지, 다시 Foreground로 돌아왔을 때 어떤 작업을 활성화해준다던지 등이 있을 수 있다.

이럴때, 특정 Activity/Fragment에서의 처리라면 해당 화면의 Lifecycle의 이벤트를 수신해서 처리할 수 있지만, 화면 레벨이 아닌 앱 레벨에서의 처리가 필요할때도 있다.

이럴때 마다 모든 Activity/Fragment의 이벤트를 수신받아 처리하기엔 과한 부분이 있다.

이를 해결하기 위해 ProcessLifecycleOwner를 사용할 수 있다.

https://developer.android.com/reference/android/arch/lifecycle/ProcessLifecycleOwner?authuser=1 

 

ProcessLifecycleOwner  |  Android Developers

Stay organized with collections Save and categorize content based on your preferences. added in version 1.1.0 belongs to Maven artifact android.arch.lifecycle:extensions:1.1.1 ProcessLifecycleOwner The android.arch Architecture Components packages are no l

developer.android.com

ProcessLifecycleOwner는 전체 어플리케이션 프로세스의 Lifecycle 이벤트를 수신할 수 있게 해 준다.


우선 아래 의존성을 추가해준다.

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.1"
}

그리고 Application 클래스를 생성하여 다음과 같은 코드를 작성해준다.

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(
            object : LifecycleObserver {
                @OnLifecycleEvent(Lifecycle.Event.ON_START)
                fun onForeground() {
                    // Do something
                }

                @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
                fun onBackground() {
                    // Do something
                }
            }
        )
    }
}

코드는 굉장히 간단하다.

Application 클래스에서 ProcessLifecycleOwner를 획득하고 LifecycleObserver를 추가해주고, ON_START, ON_STOP 이벤트에 대해 처리하면 된다.

이제 각각의 상태일 때 어떻게 처리할 것인지 자유롭게 구현하면 된다.

반응형