Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
Zohab Ali Avatar asked Dec 31 '25 03:12

Zohab Ali


1 Answers

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
    }

}
like image 136
pablobu Avatar answered Jan 01 '26 17:01

pablobu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!