Search code examples
androidandroid-lifecycle

How to detect if android application is minimized or not in Android Kotlin


I would like to detect if my application is minimized (I mean press home button) or not, using Kotlin. Note that I am not talking about any specific activity or fragment, I mean whole of the application. I need to assume three separate state for application: Showing in the view port, minimized, and completely closed. How should I detect first two states? If android lifecycle can do this, please describe how. Thank you!


Solution

  • If app home button is pressed you can check with a LifecycleObserver in Application

    inner class ApplicationObserver : LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        fun onPause() {
        }
        
    }
    

    To detect when uses swipe and kill your app you can use a Service and you can register it with

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

    or override Activity's onUserLeaveHint method which runs when home button is pressed.

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

    To detect when user swipes right and finishes your app you can use a Service and override

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

    We used this method for a showcase app which required app to be working all the time. When a customer in a shop closes the app we set an alarm and restart it again.