Tom11
Tom11

Reputation: 2519

Stopping a LocationListener Service

I want to stop LocationListener, but using a Log, I´ve found out that my service is still running after removeUpdates() method (When the location changes, it´s inserted into my log). Do you know where the problem is? Thanks in advance.

public class MyService extends Service implements LocationListener {

 private final static String TAG = "MyService";
 LocationManager lm;

     public MyService() {
     }

     ....//Other methods here

    public void onLocationChanged(Location loc) {
         Log.d(TAG, loc.toString());
         if(/*A condition, which has to stop the service when it´s time*/) 
         {
             lm.removeUpdates(this);
             lm = null;
         }
    }

    public void subscribeToLocationUpdates() {
        this.lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }

    @Override
    public void onDestroy() {
    }

}

I call this service in another Activity, onCreate method:

    ComponentName comp = new ComponentName(getPackageName(),
                 MyService.class.getName());
    ComponentName service = startService(new Intent().setComponent(comp));

Upvotes: 0

Views: 2295

Answers (1)

Mr.Me
Mr.Me

Reputation: 9276

The Service object and its lifecycle is independent of the state of your location manager. or any other object for that matter. A service represents a background part of your app. once you are done with it you can call finish() method to end it.

So in your case :

   public void onLocationChanged(Location loc) {
     Log.d(TAG, loc.toString());
     if(/*A condition, which has to stop the service when it´s time*/) 
     {
         lm.removeUpdates(this);
         lm = null;
         stopSelf(); // end this service
     }
}

Please take a look at android's Service documentation to get a general overview of its nature : Android Service

Upvotes: 2

Related Questions