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
Application
class (detecting when it is destroyed) - this is impossible, whenApplication
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 - extendApplication
class (and register it in manifest) and useActivityLifecycleCallbacks
with additional counting code:counter++
when anyonActivityStarted
andcounter--
whenonActivityStopped
. also inonActivityStopped
check if yourcounter==0
, if yes then all yourActivities
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 visibleActivities
for you and only callsonAppBackgrounded
when all are gone)