I know this is an old post and as David Wasser's answer above has been the best solutions in the past... there is now a better way of doing things.
The better way to do all of this using ProcessLifecycleOwner
, which is designed for just this. In short and right from the JavaDoc:
"Class that provides lifecycle for the whole application process."
If your application is killed, the Application lifecycle onDestroy would be called, which allows you to creatively track this how you wish. It could be as simple as setting a SharedPreference flag that you can check when the application restarts incorrectly.
Please note, you need to add appropriate android.arch
dependencies to take advantage of the new LifecycleObserver
, ProcessLifecycleOwner
, etc.
Below is an example of how you can handle each LifecycleEvent for the whole Application.
public class MyApplication extends Application implements LifecycleObserver {
@Override public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate(){
// ... Awesome stuff
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart(){
// ... Awesome stuff
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume(){
// ... Awesome stuff
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause(){
// ... Awesome stuff
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop(){
// ... Awesome stuff
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestory(){
// ... Awesome stuff
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onAny(){
// ... Awesome stuff
}
}
Here is a nice article where I learned about this along with Kotlin examples and a few more tips beyond this post: Background and Foreground events with Android Architecture Components