如何在 Android Kotlin 中检测 Android 应用程序是否最小化

问题描述 投票:0回答:1

我想使用 Kotlin 检测我的应用程序是否最小化(我的意思是按主页按钮)。请注意,我不是在谈论任何特定的活动或片段,而是指整个应用程序。我需要为应用程序假设三种不同的状态:在视图端口中显示、最小化和完全关闭。我应该如何检测前两个状态?如果 android 生命周期可以做到这一点,请描述如何做。谢谢!

android android-lifecycle
1个回答
3
投票

如果按下应用程序主页按钮,您可以使用

LifecycleObserver
 中的 
Application

进行检查
inner class ApplicationObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
    }
    
}

要检测何时使用滑动并终止您的应用程序,您可以使用服务并可以使用它进行注册

   ProcessLifecycleOwner
            .get()
            .lifecycle
            .addObserver(ApplicationObserver())

或重写 Activity 的 onUserLeaveHint 方法,该方法在按下主页按钮时运行。

/**
 * Called as part of the activity lifecycle when an activity is about to go
 * into the background as the result of user choice.  For example, when the
 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
 * when an incoming phone call causes the in-call Activity to be automatically
 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
 * the activity being interrupted.  In cases when it is invoked, this method
 * is called right before the activity's {@link #onPause} callback.
 *
 * <p>This callback and {@link #onUserInteraction} are intended to help
 * activities manage status bar notifications intelligently; specifically,
 * for helping activities determine the proper time to cancel a notification.
 *
 * @see #onUserInteraction()
 * @see android.content.Intent#FLAG_ACTIVITY_NO_USER_ACTION
 */
protected void onUserLeaveHint() {
}

要检测用户何时向右滑动并完成您的应用程序,您可以使用

Service
并覆盖

override fun onTaskRemoved(rootIntent: Intent?) {
    super.onTaskRemoved(rootIntent)

    setRestartAppAlarm()
}

我们将这种方法用于展示应用程序,该应用程序要求应用程序始终运行。当商店里的顾客关闭应用程序时,我们会设置警报并重新启动它。

© www.soinside.com 2019 - 2024. All rights reserved.