I need to make status of user offline. When I press home button onStop()
is called, that's fine. When I press back button onDestroy()
is invoked. But when I close the app from recent apps by swiping it, onStop()
or onDestroy()
isn't called.
I need to know when the app is closed from recent apps to do something (e.g make user offline).
Make a service :
Make a custom class :
Add to your activity :
Methods of
Activity
lifecycle that are to be called whenActivity
is no longer visible are not guaranteed to be called when removed from the recent tasks (treat it as "soft" version of killing an app by the system due to low memory).I suggest one of the following:
Activity
'sonResume()
/onPause()
to "make user online/offline";use
Service
that sticks to the application meaning that if the app is killed afterService
'sonStartCommand()
returns, the service will be recreated andonStartCommand()
will be called again. At this point you could "make user offline". The chain of lifecycle method calls would be:Activity
'sonStop()
->onDestroy()
* ->Service
'sonTaskRemoved()
* ->Application
'sonCreate()
->Service
'sonCreate()
->Service
'sonStartCommand()
The
Intent
passed to the method will help you recognize which component triggered the start request:Intent
!= null, meaning the request has been received from a runningActivity
instanceIntent
= null, meaning the request has been sent by the (newly created)Application
instance* Not guaranteed to be called
No, there is no clean way to get the application termination time. But I could suggest you a dirty trick to use a service to update your application (offline functionalities) for every after n minutes.
When OS kill your application, it will remove all associated services and broadcast receiver along with it.