Search code examples
androidserviceandroid-service

super call in Service lifecycle


When I was reading this link https://developer.android.com/guide/components/services#LifecycleCallbacks,I came across this statement

Note: Unlike the activity lifecycle callback methods, you are not required to call the superclass implementation of these callback methods.

Can anyone explain why it is not required to call superclass and on what scenario we can add superclass implementation?

Thanks


Solution

  • In the activity lifecycle the callbacks are made because we need to run the existing code on those methods of the Activity class.

    For example

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate( savedInstanceState );
            // your code
        }
    

    In this method we say the compiler to not only run our code but also the existing code in the onCreate method of the Activity class. The existing code takes care of assigning the context to the activity, setting the actionBar etc. If you wanna know more about what the existing onCreate method code does, you can navigate through that method in the Activity class.

    But in the case of Service we need not run the existing code ( of course there are no existing code in those methods ) and the system itself takes care of what to do and only notifies us about what lifecycle the service is going through so that we can code according to the lifecycle our service is in.

    For example

        @Override
        public void onDestroy() {
            // You can make a toast here to notify the user that the service has ended
        }
    

    This method in the Service class notifies that the service is being destroyed. You can navigate through this method in the Service class and see no code has been written on that method. So we can conclude that the method is only notifying us about the destroying of the service.

    But you can still make a super call on the method, Like below

       @Override
        public void onDestroy() {
            super.onDestroy();
        }
    

    But we have no changes in the running of the code since the onDestroy method in the super class is empty. More precisely we don't need the existing code (in this case it's empty) to what we expect that to do.

    For your last question,

    You should implement a super call when you wanna run the existing code. If you just wanna know if the method is called and you don't wanna run the existing code but only your code on the subclass you should not implement a super call