Lenin
Lenin

Reputation: 492

How to know once user toggle ON/OFF GPS?

Please tell a way to know in my app, once user ON/OFF the GPS, so that i can switch the Location provider according to GPS availability. My app is a service and I am registering both providers in onCreate() method of my Service class.

Upvotes: 1

Views: 195

Answers (1)

Reed
Reed

Reputation: 14974

If you invoke LocationManager.requestLocationUpdates(...) in your LocationListener you would override onProviderDisabled and onProviderEnabled and within those two methods you would do whatever you want - switch the provider you are using - in this case.

If you need further explanation, just comment to let me know.

EDIT:

So should i remove the listener like this locationManager.removeUpdates(locationListener); in onProviderEnabled() before registering for the listener according to their availabilty?

No. Use 2 conditional if statements like so:

LocationManager locMan = (LocationManager)Context.getSystemService(Context.LOCATION_SERVICE);
if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
    //request updates for gps provider
}
if (locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
    //request updates for network provider
}

This way, if both are on, you will use both, but if only one is on, you will only use that one. If both are off, you of course will use neither.

And you may want to additionally do:

 if (!locMan.isProviderEnabled(LocationManager.GPS_PROVIDER) && 
        !locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
            //do whatever you want for when both are disabled.
        }

Upvotes: 2

Related Questions