Some times application be closed by pressing home button and onDestroy() doesn't call. I want to call a method when whole application is closed and I'm not going to call my method in all activities's onDestroy().
Asked
Active
Viewed 4,022 times
3
-
2Possible duplicate of [Is it possible to detect exit of an application?](http://stackoverflow.com/questions/16298795/is-it-possible-to-detect-exit-of-an-application) – Apr 13 '16 at 06:02
-
May be an extra service will do the trick, http://stackoverflow.com/questions/24406508/how-to-detect-application-exit-on-android create and override the method.! – MKJParekh Apr 13 '16 at 06:08
-
you can check if the process is alive or not. http://stackoverflow.com/questions/4212992/how-can-i-check-if-an-app-running-on-android – Muhammad Babar Apr 13 '16 at 07:10
2 Answers
2
implements LifecycleObserver inside appication class an then use as blow:
public class App extends Application implements LifecycleObserver{
@SuppressLint("CheckResult")
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onMoveToForeground() {
}
@SuppressLint("CheckResult")
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onMoveToBackground() {
}
}
Also can use other events like Lifecycle.Event.ON_DESTROY or ON_CREATE

Erfan Eghterafi
- 4,344
- 1
- 33
- 44
-1
Application does not close on home button press.But it goes in background.
When you Application goes in background(Your front activity goes in background) it calls onStop() Method(Activity is not visible now).So you should do all stuff here.
There is no such call back the Application class. Which tell you that application is destroyed. If you want to fire an event when application is fully closed.You should check your application's activity stack.If it does not have any activity than your application is closed. You should check it from a service.

Navin Gupta
- 793
- 6
- 20
-
Yes I know, but I want to detect if my app is showing now or is destroyed or is running in background – Erfan Eghterafi Apr 13 '16 at 06:11
-
onStop means that particular activity is in the background, would be called when app goes in background, but also a lot of other situations (another acitivity in app is opened, etc.). So onStop doesn't really address this person's issue. – Bourne Sep 19 '17 at 13:34
-
@Bourne I have already mentioned in my answer that there is No way to detect that your application is completely closed. You can do some tricks to get closer result for that problem – Navin Gupta Sep 19 '17 at 14:02