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 the service stop itself?
By calling stopSelf() , the service stops. Please make sure that no thread is running in the background which makes you feel that the service hasn't stopped. Add print statements within your thread. Hope this helps.
Fundamentals of Android Services it can be stopped explicitly using stopService() or stopSelf() methods. with the service effectively by returning an IBinder object. If the binding of service is not required then the method must return null.
A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. The service must stop itself by calling stopSelf() , or another component can stop it by calling stopService() .
You can add a shutdown() method into your AIDL interface, which allows an Activity to request a stopSelf() be called. This encapsulates the stopping logic and gives you the opportunity to control the state of your Service when it is stopped, similar to how you would handle a Thread .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With