How to unregister the Listener and stop the detector service

In my application, I have a broadcast receiver that, after receiving a keyword in an SMS message, starts a service that tracks the GPS location of the phone. I use this -

context.startService(new Intent(context,TrackGPS.class)); 

I also need to be able to stop the service after receiving another keyword in the SMS message, I tried to do this, but the GPS sensor is still tracking the location and the GPS icon is blinking at the top of the screen. I tried to do this with

 context.stopService(new Intent(context, TrackGPS.class)); 

I suppose this could be because the GPS listener must be unregistered. Can someone help me in getting this service to stop + stop GPS tracking after receiving the text? Thank you in advance.

Decision

 @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; } 
+4
source share
2 answers

I do not think your problem is stopping the service. By killing your service, you are not killing the LocationListener object, which is still looking for updates.

I would do the following.

Instead of stopping and starting your services, just start your service every time you need to do something (start listening or stop listening).

Add additional information about the intent that you use to tell you what you want to do, for example:

 Intent GPSService = new Intent(context, TrackGPS.class); GPSService.putExtra("IsStartTracking", true); context.startService(GPSService); 

In your redefinition of the onStart method of your service, you can register and unregister locations in one instance of your LocationManager based on the value "IsStartTracking"

 boolean startListening = intent.getExtras().getBoolean("IsStartTracking"); 
+1
source

Assuming you are creating a TrackGPS service and an Android service when the classes are connecting and disconnecting from your service, you can create a counter that keeps track of the clients that are connected, and when the last client is unconnected, disconnects its listener to GPS.

I assume that if you register a LocationListener, then you can figure out how to get rid of the service. There is an example of how clients should use bind () and unbind () in the Service Documentation

0
source

Source: https://habr.com/ru/post/1336856/


All Articles