Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity crash lifecycle method - android

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.

like image 587
David Lasry Avatar asked Jul 13 '16 10:07

David Lasry


People also ask

What is Android activity life cycle method?

An Android activity goes through six major lifecycle stages or callbacks. These are: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() .

How many methods are there in Android activity lifecycle?

There are seven methods that manage the life cycle of an Android application: onCreate()

What is the difference between onPause () onStop () and onDestroy () lifecycle methods?

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().

Which lifecycle method is called to make an activity visible?

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.


2 Answers

The UncaughtExceptionHandler is perfect for catching crashes.

like image 99
M0CH1R0N Avatar answered Oct 10 '22 23:10

M0CH1R0N


Unfortunately, you can't detect sudden crashes through onDestroy or onStop methods. Your options are:

  1. 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.

  2. 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.

  3. 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.

like image 45
Akeshwar Jha Avatar answered Oct 10 '22 22:10

Akeshwar Jha