I start a service in an activity then I want the service to stop itself after a while.
I called stopSelf() in the service but it doesn\'t work.
How to make t
Use stopSelf() to stop a service from itself.
If by "doesn't work" you mean the process doesn't get killed, then that's how android works. The System.exit(0)
or Process.killProcess(Process.myPid())
will kill your process. But that's not the Android way of doing things.
HTH
By saying "doesn't work", I guess you mean that the onDestroy()
-method of the service is not invoked.
I had the same problem, because I bound some ServiceConnection to the Service itself using the flag BIND_AUTO_CREATE. This causes the service to be kept alive until every connection is unbound.
Once I change to use no flag (zero), I had no problem killing the service by itself (stopSelf()
).
Example code:
final Context appContext = context.getApplicationContext();
final Intent intent = new Intent(appContext, MusicService.class);
appContext.startService(intent);
ServiceConnection connection = new ServiceConnection() {
// ...
};
appContext.bindService(intent, connection, 0);
Killing the service (not process):
this.stopSelf();
Hope that helped.
I know this is an old question, but in my case (floating window as service) I had to remove the view first, and then call stopSelf()
.
windowManager.removeView(floatingView);
stopSelf();
Another dirty hack not mentioned here is to throw an exception like NPE. One day I needed to stop InputMethodService and this hack was useful.
stopForeground(true);
stopSelf();