In my App I have a broadcast receiver that upon receiving a keyword in an SMS message, it starts a service that tracks the GPS location of the phone. I do this using –
context.startService(new Intent(context,TrackGPS.class));
I also need to be able to stop the service upon receiving another keyword in an SMS message, I have tried to do this but the GPS sensor still tracks the location and GPS icon flashes at the top of the screen. I tried to do this using –
context.stopService(new Intent(context, TrackGPS.class));
I figure this might be because the GPS listener needs to be unregistered. Can anyone help me in getting this service to stop + stop the GPS tracking upon receipt of a text? Thanks in advance.
Solution
@Override
public int onStartCommand(Intent GPSService, int flags, int startId) {
boolean startListening = GPSService.getExtras().getBoolean("IsStartTracking");
if (startListening == true){
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else {
lm.removeUpdates(this);
stopSelf();
}
return 1;
}
I don’t think your issue is stopping the service. By killing your service you are not killing the LocationListener object that is still looking for updates.
I would do the following.
Instead of stopping and starting your services, simply start your service every time you need to do something (Start listening or stop listening).
Add an extra to the Intent you use to tell you what you want to do, something like:
In your onStart method override of your service, you can now register and unregister location listeners on a single instance of your LocationManager based on the value of “IsStartTracking”