androidandroid-serviceandroid-intentservice

Does stopSelf() guarantee Service stopping (and HOW)? if so, is return required (in case stopSelf called internally)?


I Have questions about how Service and IntentService function. The points to ask about are below:

Does calling stopSelf() manually in Service (or IntentService) guarantee the service to stop?

If stopSelf() is called manually somewhere in the Service, will the code following the call be executed?

// As I know, calling stopSelf() can stop code execution in case it throws an exception, else I can't find a logic for that.


Solution

  • Does calling stopSelf() somewhere in Service (or IntentService) guarantee service to stop?

    Yes, it does.

    And does a return statement mandatory to not execute code after stopSelf() call?

    return is still needed if the function has a return type other than void (otherwise your code won't compile). The return statement most likely will be executed as stopSelf() results in stopping Service asynchronously.

    As I know, calling stopSelf() can stop code execution in case it throws an exception, else I can't find a logic for that.

    By calling stopSelf() you notify the system that Service is done with its "job" so the system could release resources the Service is holding. This is very similar to execution of Activity's onBackPressed() that is called when user presses the back button - the system finishes the Activity releasing resources.