Search code examples
androidandroid-activitydestroy

How much time can be taken inside onDestroy() before the activity is killed?


I know my question caption must have sounded really vague. But let me clear it out here.

Say I have an android application over a middleware stack. In onCreate() of my activity, I initialise my middleware modules.

In its onDestroy(), I must de-initialise the middleware. Now my middleware calls may take quite some time to process. So I want to know how much time the onDestroy() function has, and see whether my deinitialisation can take place within that time.

Is it reasonable to keep my de-init in the onDestroy()?

Also, suppose I initialise the middleware in onCreate() of activity A1. On a button click, activity A1 switches to activity A2. In low memory situations, the LMK will kill the activity that has not been in use for some time. In such a case, won't activity A1 be killed? When activity A1 is killed, will all instances I create in A1 also get destoryed?

Regards, kiki


Solution

  • I believe you are rather confused to ask this question.

    In order to get a good comprehension of what is happening, you should take a look at the lifecycle graphs that can be found on developer.android.com:

    You will see that Activity.onDestroy() only gets called in the case of a controlled shutdown of the activity - something that happens extremely rarely, as the Android OS can kill your process in a variety of states without ever calling your onDestroy() method.

    What and why do you need to de-initialize?

    • If you're worried about releasing resources, then most of them will get released anyway when/if your process is killed.
    • If you are worried about saving the user's data (your application's state) then you should override onSaveInstanceState() and onRestoreInstanceState()

    If you really want an answer to your question, then here it is:

    • While it is running onDestroy(), your app has (probably) as much time as it would like to - the fact that it is even running onDestroy() means that the OS did not select it to be killed. But it will most likely not matter: for one, onDestroy will never be run in most apps, and if the OS changes its mind and decides that your app must die, it will kill it even if it is running onDestroy.