Search code examples
androidandroid-ondestroyapplication-close

How to detect when application is closed by a user in android?


I know that, unlike onCreate(), Application class does not have a onDestroy() method. But I wanted to know when my application is closed (or it is not visible on screen anymore). After all, whatsapp and many more similar chat applications can detect when user has left the app, and can record user's last online time. I want to achieve a similar thing. Also, when the application is destroyed, I want to detach all listeners attached to firebase databse.

I have already seen this question, but the accepted answer there is unreliable. So, what is the workaround for onDestroy() for me.


Solution

  • if you are talking about Application class (detecting when it is destroyed) - this is impossible, when Application gets killed developer shouldn't (and don't) have option for executing own code (as it may e.g. restart app from scratch)

    but you are talking about app visibility, probably any Activity present on screen - extend Application class (and register it in manifest) and use ActivityLifecycleCallbacks with additional counting code: counter++ when any onActivityStarted and counter-- when onActivityStopped. also in onActivityStopped check if your counter==0, if yes then all your Activities are in background, so app isn't visible on screen (still it doesn't mean that its destroyed/killed)

    edit: check out THIS example. or inspect supporting class ProcessLifecycleOwner (which probably is counting visible Activities for you and only calls onAppBackgrounded when all are gone)