If we want to get a single GPS fix in Android we actually use the known function requestSingleUpdate() with LocationManager.GPS_PROVIDER, right?
Now i was exactly doing this in my function getLocation() with GPS turned on, but the device is not automatically going to establish a connection, unless i manually turn off the GPS and then turn it on again. requestSingleUpdate() for the network provider works flawlessly, i just don’t know why this doesn’t go for the GPS fixing.
Here is a part from my source code:
getLocation() is run by another object with a timer every 2 minutes.. in getLocation() if the GPS and Network are on, it tries to get a GPS fix in the first minute and then it fetches the network location if there is no GPS fix available.
public boolean getLocation() {
// DEBUG
Log.d("GPS Connection", "Entering getLocation()");
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gpsEnabled && !networkEnabled)
return false;
if(gpsEnabled && networkEnabled) {
// DEBUG
Log.d("GPS Connection", "Request GPS Data");
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, gpsLocationListener, Looper.getMainLooper());
gpsGetLocationTimeout = new Timer();
gpsGetLocationTimeout.schedule(new GetNetworkLocation(), GPS_MAX_CONNECTION_TIME_MS);
}
...
From the Android documentation:
GPS can take a long time to get from a cold start. You may never get a GPS if you are indoors, in a parking structure, surrounded by tall buildings, have a crappy phone, or if the GPS Satellite Gods are in a funny mood.
In some applications, we will do something like request a GPS location, then if it hasn’t arrived after 60 seconds, cancel the request so that we don’t kill the phone’s battery with a GPS RX left on semi-permanently.
You can request last known location and check its age and decide if it is recent enough to use. Network location is fast and cheap (in terms of battery use) and a good strategy is to use network location until you get GPS.
My experience coding GPS in Android is that the GPS is going to do what it wants to do which is in many ways not what the documentation leads you to expect. GPS needs to be treated as something which may or may not be available and the logic of your program can be designed to handle that.