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.
if you are talking about
Applicationclass (detecting when it is destroyed) - this is impossible, whenApplicationgets 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
Activitypresent on screen - extendApplicationclass (and register it in manifest) and useActivityLifecycleCallbackswith additional counting code:counter++when anyonActivityStartedandcounter--whenonActivityStopped. also inonActivityStoppedcheck if yourcounter==0, if yes then all yourActivitiesare 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 visibleActivitiesfor you and only callsonAppBackgroundedwhen all are gone)