如何在 android 中检测应用何时进入前台
How to detect whenever app comes to foreground in android
我已经阅读了很多关于 how to detect when app comes to foreground
的内容,但找不到满意的答案。他们中的大多数都在使用 onResume() 和 onClose() 方法并保持计数等
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.
所以这就是为什么我想确保在 android 默认情况下没有任何方法可以检测到这一点,如果没有,那么最好的方法是什么?
您应该在 onResume() 方法中输入密码,因为这将是再次 activity 运行 之前调用的最后一个方法。
现在您可以在创建应用时将 LifecycleObserver 添加到应用中,以检测您的应用何时进入 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
}
}
您可以使用 onWindowFocusChanged。
我已经阅读了很多关于 how to detect when app comes to foreground
的内容,但找不到满意的答案。他们中的大多数都在使用 onResume() 和 onClose() 方法并保持计数等
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.
所以这就是为什么我想确保在 android 默认情况下没有任何方法可以检测到这一点,如果没有,那么最好的方法是什么?
您应该在 onResume() 方法中输入密码,因为这将是再次 activity 运行 之前调用的最后一个方法。
现在您可以在创建应用时将 LifecycleObserver 添加到应用中,以检测您的应用何时进入 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
}
}
您可以使用 onWindowFocusChanged。