ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [AOS] Check App Status (Background or Foreground)
    2023. 6. 30. 15:18
    ๋ฐ˜์‘ํ˜•

     

     

    ๐Ÿ‘ฎ๐Ÿป‍โ™€๏ธ
    ์•ฑ์—์„œ ํ™ˆ ์ง„์ž…ํ–ˆ๋‹ค๊ฐ€ ๋‹ค์‹œ ์ง„์ž… ์‹œ์— ์‚ฌ์šฉ์ž ์ธ์ฆ์„ ์•ˆํ•˜๋„ค์š”? ๋ณด์•ˆ์ด ๋„ˆ๋ฌด ์•ฝํ•œ๊ฑฐ ์•„๋‹Œ๊ฐ€์š”?
    ๋„ค...? ๋„ค... ๋ณด์•ˆ ๊ฐ•ํ™”ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค... ๐Ÿ˜ญ
    ๐Ÿถ

     

     

     

     

     

    ์•ฑ ์ƒํƒœ๊ฐ€ Background์ธ์ง€ Foreground์ธ์ง€ ์ƒํƒœ๋ฅผ ์ฒดํฌํ•˜์—ฌ ๊ฐ๊ฐ์˜ ์ƒํƒœ์— ๋”ฐ๋ฅธ action์„ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ 2๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค.

     

    Observer๋ฅผ ์ƒ์„ฑํ•˜๊ณ , Androidx.lifecycle ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ implementationํ•˜์—ฌ processLifecycleOwner๋ฅผ ์ด์šฉํ•œ ๋ฐฉ๋ฒ•๊ณผ,

    ๊ฐ„๋‹จํ•˜๊ฒŒ ActivityManager์˜ RunningAppProcessInfo ๊ฐ’์„ ์ด์šฉํ•œ ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.

     

     

    ProcessLifecycleOwner

    1. implementation for ProcessLifecycleOwner

    dependencies {
        ...
        implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
        implementation "android.arch.lifecycle:extensions:1.1.1"
        implementation 'android.arch.lifecycle:common:1.1.1'
        ...
    }

     

    2. Observer ํด๋ž˜์Šค ์ƒ์„ฑํ•˜๊ธฐ

    class OnAppObserver:LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onStart() {
            // to do when app is in foreground
        }
        
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onStop() {
            // to do when app is in background
        }
        
    }

     

    3. Observer ์„ค์ •

    class MainApplication : Application() {
        override fun onCreate() {
            super.onCreate()
        
            ProcessLifecycleOwner.get().lifecycle.addObserver(OnAppObserver())
            ...
        }
    }

     

     

    ActivityManager.RunningAppProcessInfo

    override fun onStop() {
        super.onStop()
        
        val processInfo = RunningAppProcessInfo()
        ActivityManager.getMyMemoryState(processInfo)
        if (processInfo.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
        // to do when app is in background
        }
    }

     

    ์œ„ ์ฝ”๋“œ๋Š” onCreate()์— ๊ตฌํ˜„ํ•˜๋ฉด ํ•ญ์ƒ Foreground ์ƒํƒœ๋กœ ์ฒดํฌ๋˜๊ธฐ ๋•Œ๋ฌธ์—, ์•ฑ์ด background ์ƒํƒœ๋กœ ์ง„ํ–‰๋  ๋•Œ ํ˜ธ์ถœ๋˜๋Š” onStop() ํ•จ์ˆ˜๋ฅผ overrideํ•˜์—ฌ ๊ตฌํ˜„ํ•ด์ฃผ์—ˆ๋‹ค.

     

     

     

    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.