Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StopService does not call onDestroy immediately

I am using the following statement to stop a download service (that extends IntentService) running in the background:

    context.stopService(intent);

But this statement is not calling the onDestory() method of service immediately, It is taking sometime to call onDestroy() method of service.

@Override
public void onDestroy() {
    Log.d("JSLog", "on destroy called");
    super.onDestroy();
}

What should I do that after hitting the stopService() statement, it should immediately called onDestroy() method of the service.

like image 385
Kanika Avatar asked Dec 11 '22 08:12

Kanika


1 Answers

In my case, I followed the tutorial at Android Developers, which uses a ServiceConnection. In the example code, they call unbindService() but never stopService(). So I added a call to stopService() to stop it, but still onDestroy() never got called.

From the documentation of Context.stopService():

Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed.

I interpreted this as it's okay to call stopService() or stopSelf() first, and then unbindService() afterwards (I'm using BIND_AUTO_CREATE) - and that the service would be stopped/destroyed upon calling unbindService().

But it turns out that this isn't the case. When I moved things around so that I'm calling unbindService() first and stopService() after that, my onDestroy() gets called immediately.

like image 169
Magnus Avatar answered Dec 13 '22 23:12

Magnus