Search code examples
javaandroidstaticoncreateondestroy

Static blocks of classes not called onCreate after onBackPressed


In my app when onCreate occurs I call a static method of another class. E.g. ClassName.method(). This second class contains a static block which is also executed when the method is called. This is exactly what I want to happen.

However when I press the back button and return to the app, onCreate is again called (back caused onDestroy to execute) and that other method is called but the static block is not. This isn't the case when I manually close the app from running in the background (the swipe technique) and then reopen it. In that particular case the static block is called.

Why is the static block of the class not called when the app restarts after onBackPressed?

Thank you.

Update:

It seems to me that the class is not removed from memory even after onDestroy when back is pressed. I was under the impression that everything would reinitialise when onCreate is called again. However this does not seem to be the case. Is there a way to remove the class on calling onDestroy?


Solution

  • A static block in a class is called during the initialization of the class. Since, a class is loaded (and initialized) only once, the static blocks in it are called only once.

    May be you shouldn't be using the static block at all. Just put the code in a static method and call it whenever you want.