Search code examples
androidbroadcastreceiverandroid-lifecycleondestroy

Is onDestroy called only if you explicitly call finish() ?? or are there any exceptions?


I have a LocalBroadcastReceiver and I am unregistering it in my ondestroy().

Now i read about ondestroy() mentioned in these two SO answers is-ondestroy-not-always-called and why-implement-ondestroy-if-it-is-not-guaranteed-to-be-called and as well as in Androi Docs that

onDestroy will be called if you explicitly call finish();

But why in my case I am not calling finish() but still ondestroy() is getting called everytime in all of my Android devices. Also according to you guys where are the cases where ondestroy() not get called up.

Also even if Android will kill my app(due to less memory) I don't need to worry as Android is going to kill my whole app so receiver will ultimately get killed.(So there won't be any Memory Leak).

So for my use case which cases are there where ondestroy() is not going to get called up.


Solution

  • But why in my case I am not calling finish() but still ondestroy() is getting called everytime in all of the Android devices.

    The default implementation of onBackPressed() — what is triggered by the BACK button — calls finish().

    where are the cases where ondestroy() not get called up.

    1. If you crash with an unhandled exception

    2. If your process is terminated in an urgent fashion (e.g., the system needs RAM to process an incoming phone call)

    3. If the user clicks "Force Stop" on your app's screen in Settings

    4. On a few devices, if the user terminates your process using a manufacturer-supplied task manager

    Also even if Android will kill my app(due to less memory) I don't need to worry as Android is going to kill my whole app so receiver will ultimately get killed

    Yes, because your entire process will be terminated.