I'm developing an app which in a case of crash, needs to save some data with the time of the crash. Now, I'm saving the data in onDestroy() like this:
@Override
protected void onDestroy() {
saveState();
super.onDestroy();
}
But whenever I crash my app on purpose, onDestroy() is not called and my data is not saved.
My question is, how can I save my data on a crash? Which approach should I take? Because I need the time of the crash to be also saved, it's mandatory.
An Android activity goes through six major lifecycle stages or callbacks. These are: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() .
There are seven methods that manage the life cycle of an Android application: onCreate()
Difference between onPause(), onStop() and onDestroy() So, onPause() is logically before onStop(). From onPause() it is possible to call onResume() but it is not possible once onStop() is called. Once onStop() is called then onRestart() can be called. onDestroy() is last in the order after onStop().
The onStart() method runs. It gets called when the activity is about to become visible. After the onStart() method has run, the user can see the activity on the screen.
The UncaughtExceptionHandler is perfect for catching crashes.
Unfortunately, you can't detect sudden crashes through onDestroy
or onStop
methods. Your options are:
Use try-catch blocks. Wrap up the probable places of crash in try block and catch the exceptions in the catch block, then you can gracefully close the app.
Implement try-catch blocks at susceptible placecs. Then, you can integrate crashlytics to your app and log the exceptions to crashlytics in the catch block. Let the app used thoroughly by a couple of users and then at crashlytics analytics, you can see the places where the app is actually crashing most of the times.
Use acra. It catches exceptions, retrieves lots of context data and send them to the backend of your choice.
You can always record the system time in the catch block and save your data there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With