首页 > 解决方案 > 如何在Android Kotlin中检测android应用程序是否最小化

问题描述

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

标签: androidandroid-lifecycle

解决方案


如果按下应用程序主页按钮,您可以使用LifecycleObserverin进行检查Application

inner class ApplicationObserver : LifecycleObserver {

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

要检测何时使用滑动并杀死您的应用程序,您可以使用 Service 和 u

并注册它

   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() {
}

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

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

    setRestartAppAlarm()
}

我们将此方法用于需要应用程序一直运行的展示应用程序。当商店中的客户关闭应用程序时,我们会设置警报并重新启动它。


推荐阅读