Zohab Ali
Zohab Ali

Reputation: 9574

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?

Upvotes: 2

Views: 1601

Answers (3)

Sreedev P R
Sreedev P R

Reputation: 131

You could use onWindowFocusChanged.

Upvotes: 1

pablobu
pablobu

Reputation: 1311

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
    }

}

Upvotes: 7

wyoskibum
wyoskibum

Reputation: 1859

You should do the passcode in the onResume() method as that would be the last method called prior to the activity running again.

Upvotes: 1

Related Questions