Home > Mobile >  Why doesn't android Service call super.onDestroy?
Why doesn't android Service call super.onDestroy?

Time:11-17

I have a question while looking at the Android Service example.

https://developer.android.com/guide/components/services

Android Developer Service Example Image

Why not call super.onDestroy even though They override onDestroy in this example? And What is the role of Android Service onDestroy?

I tried to reading git source on Android.

I removed super.onDestroy and took a capture in profiler. (But, Service wasn't Deallocated Whether I add it or not)

CodePudding user response:

Q1:

Why not call super.onDestroy even though They override onDestroy in this example?

Ans: The super method does nothing here. It just a good practise to include the super call if you override the Native Android classes.

Further, this may not be true for private one as I always override the method from a 3rd party library without calling there super method. It depends.

REF: AOSP - frameworks/base/core/java/android/app/Service.java

...
public abstract class Service extends ContextWrapper implements ComponentCallbacks2,
        ContentCaptureManager.ContentCaptureClient {
   ...    
   /**
     * Called by the system to notify a Service that it is no longer used and is being removed.  The
     * service should clean up any resources it holds (threads, registered
     * receivers, etc) at this point.  Upon return, there will be no more calls
     * in to this Service object and it is effectively dead.  Do not call this method directly.
     */
    public void onDestroy() {
    }
    ...
}

Q2:

What is the role of Android Service onDestroy?

Ans: It is a message sent out by low level API call. It just a notification which tell you that your service is going to be destroyed, please clean the resource before the end of this block(or just ignore it if there is nothing important for you to do). And even you do nothing there, the service will be destroyed since it just a notification. In normal circumstance, you have no control of the life cycle there.


UPDATED

So I forget to answer your title question. The behaviour is a bit contradict to what I said in Ans 1.

IMO, I think the website example just want to give you an idea the service will be destroyed there by creating a toast there. There is no difference whether or not they add super.onDestroy there.

But again, calling onDestroy in the website example seems to violate the recommendation in the comment of the Service#onDestroy.

Welcome anyone to correct me

  • Related