Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop service by itself?

Tags:

android

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?

like image 693
Mak Sing Avatar asked Dec 11 '09 09:12

Mak Sing


People also ask

How do I stop Android service by 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.

How do I stop a service explicitly?

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.

How do I stop a service started?

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() .

How do I stop a service from another activity?

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 .


1 Answers

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.

like image 92
AlikElzin-kilaka Avatar answered Sep 19 '22 15:09

AlikElzin-kilaka