How to unregister Listener & stop service from wit

2019-06-28 07:54发布

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;
}

2条回答
爷、活的狠高调
2楼-- · 2019-06-28 08:04

assuming you are creating the TrackGPS service and an Android Service, when classes bind and unBind from your service you can create a counter that keeps track of clients which are bound and, when the last client is unbound, shutdown its listener to the gps.

I'm assuming if you are registering the LocationListener then you can figure out how to unbind from the service. There is an example of how clients should use bind() and unbind() at the Service documentation

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-28 08:12

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:

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

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"

boolean startListening = intent.getExtras().getBoolean("IsStartTracking");
查看更多
登录 后发表回答