How to stop service by itself?

Solution 1:

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.

Solution 2:

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.

Solution 3:

since you didnt publish your code, i cant know exactly what you are doing, but you must declare WHAT you are stopping:

this.stopSelf();

as in:

public class BatchUploadGpsData extends Service {
    @Override
    public void onCreate() {
        Log.d("testingStopSelf", "here i am, rockin like a hurricane.   onCreate service");
        this.stopSelf();
    }

Solution 4:

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