Android Studio 0.4.6
Hello,
I have a code snippet here. And I have often been confused if super should be the first line of execution or the last. Normally, I make it the first call so that the default properties can be set in the parent class. However, I was looking at some code that does it before. I am just wondering does it make any difference?
@Override
protected void onDestroy() {
mBroadCastMgr.unregisterReceiver(receiver);
super.onDestroy();
}
As in the docs:
onDestroy() = This callback is called before the activity is destroyed by the system.
Sample Illustration:
/** Called just before the activity is destroyed. */
@Override
public void onDestroy() {
super.onDestroy();
Log.d(msg, "The onDestroy() event");
}
Popularly mentioned by user @Cristian (don't know where)-
It really depends on what you want to do in your onDestroy. This is what super.onDestroy
does (in that order):
1) Dismiss any dialogs the activity was managing.
2) Close any cursors the activity was managing.
3) Close any open search dialog.
Having said that,
"If the logic you put inside onDestroy has something to do with those three things that android does, then you may have to worry about the order. Otherwise, and in most of the cases, it does not matter."
In general when you are creating something your code goes last when you are destroying something your code goes first. It is like in real life imagine adding something to something existing and removing something from something existing
In onDestroy
, definitely, place your code first the activity is not valid after super.onDestory
Another interesting situation in onSaveInstanceState
you should place your code first because it is super.onSaveInstanceState who does the actual saving (and you thus add what extra you want to save, first)
If you want to implement cleanup logic safely, you can use next pattern:
@Override
protected void onDestroy() {
try {
mBroadCastMgr.unregisterReceiver(receiver);
} finally {
super.onDestroy();
}
}
In general, necessarity of super class call should be checked in all overriden methods using documentation (method javadoc) or super class' source code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With