ksu
ksu

Reputation: 902

Android Activity onDestroy() is not always called and if called only part of the code is executed

onDestroy() is not always called. If called, only part of the code is executed. And most of the time in LogCat I only see the message "gps state on destroy called first". Why is that?

protected void onDestroy() {
    super.onDestroy();
    Log.d("on destroy called", "gps state on destroy called first");

    editor.putBoolean("gpsOn", false);
    Log.d("on destroy called", "gps state on destroy called second");
    editor.commit();

    Log.d("on destroy called", "gps state on destroy called third");
    stopRouteTracking();
    Log.d("on destroy called", "gps state on destroy called  fourth");
}

Upvotes: 42

Views: 97092

Answers (3)

Karan
Karan

Reputation: 356

In the android developer documentation here, you can see that -

for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed. Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage.

and onStop() and onDestroy() both are marked as killable.

This may be the reason that only part of the code written in onDestroy() is being called since process can be destroyed at any time after it executes onStop().

Upvotes: 17

HaydenKai
HaydenKai

Reputation: 880

@Chris's answer is correct, however your issue where only part of your code is called can arise from the call to super.onDestroy() before calling your code. super.onDestroy() should be called at the end because then your code will be called before it is destroyed.

Upvotes: 3

Chris
Chris

Reputation: 959

Take a look at this:

Activity OnDestroy never called?

And this:

http://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29

Basically, there's never a guarantee that onDestroy() will be called, and in some cases processes such as your app will be killed directly, bypassing the method call anyway.

Upvotes: 29

Related Questions