Search code examples
androidandroid-activitykotlinforeground

How to detect whenever app comes to foreground in android


I have read alot about how to detect when app comes to foreground but unable to find any satisfactory answer. Most of them are using onResume() and onClose() methods and keeping count etc

I am working on a crypto-currency app and I have to ask for passCode whenever app comes to foreground, which is very critical in my case. It must ask for passCode every time.

So that is why I want to assure that isn't there any method to detect this in android by default if not then what is the best approach?


Solution

  • Now you can add a LifecycleObserver to your app when it's created to detect when your app goes to foreground/background.

    class MyApp : Application() {
    
        private lateinit var appLifecycleObserver : AppLifecycleObserver
    
        override fun onCreate() {
            super.onCreate()
            appLifecycleObserver = AppLifecycleObserver()
            ProcessLifecycleOwner.get().lifecycle.addObserver(appLifecycleObserver)
        }
    }
    
    
    class AppLifecycleObserver() : LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onEnterForeground() {
            // App entered foreground
            // request passpharse
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onEnterBackground() {
            // App entered background
        }
    
    }