11

Whats the correct way of calling super.onStop(), i.e, when unregistering a listener?

I have seen:

protected void onStop() {
  sensorManager.unregisterListener(this);
  super.onStop();
}

OR

protected void onStop() {
  super.onStop();  
  sensorManager.unregisterListener(this);
}
1
  • I've always been told that super should be called as the first thing of an overrode method (that you intend to super!) In practice, I don't think it actually matters, and that is more of a "clean code" way of doing things.
    – Eric
    Jun 25, 2011 at 23:46

3 Answers 3

8

You should always call it first, mostly as a protection mechanism: if there is an exception then the superclass instance method will already have been called.

3

It doesn't matter. Unless you are dependent on some state continuing to be initialized (and as far as any framework classes are concerned I can guarantee you aren't) you can freely call it after the superclass. If the superclass throws an exception your whole app is going to crash, so there is no reason to order one way or the other due to that.

That said, just for consistency putting these calls on the first line is nice because that is where people expect to see them and it will help avoid you making mistakes in the future such as deleting code in the method and accidentally deleting the call to the super class.

2

From what i read, methods you override that are part of component destruction (onPause(), onStop(), onDestroy(), etc.), you should do your work first and chain to the superclass as the last thing. That way, in case Android cleans up something that your work depends upon, you will have done your work first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.