Android: GPS fallback from fine to coarse
Greetings,
Does anyone know how I can get coarse GPS coordinates when I don't have a fix and get fine GPS coordinates when I have a fix?
I've tried googling for some sample code to no avail.
I did find this: http://www.androi开发者_StackOverflowd10.org/index.php/articleslocationmaps/226-android-location-providers-gps-network-passive
But I don't know how to implement the fallback to coarse/upgrade to fine.
I hope someone can help. Thanks in advance,
You can find an excellent introduction to the subject in the documentation. The basic idea is that you enable listening for updates from different providers. When a new location is received, you compare it to the previous stored location (a sample function is provided in the above link).
A location object has an getAccuracy
that you can use to measure its accuracy. You should also set up a timer so that you know how long has passed after a location provider has provided an update. If more than two minutes have passed after GPS provider has given you an update, then start listening for network updates. While listening for network updates, if GPS gives you a new update, then switch to fine location.
You can get the last know location using the code below. It gets the location providers and loops over the array backwards. i.e starts with GPS, if no GPS then gets network location. You can call this method whenever you need to get the location.
private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
精彩评论