Android: GPS fallback from fine to coarse

戏子无情 提交于 2019-11-30 18:06:23

问题


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.android10.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,


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/4554569/android-gps-fallback-from-fine-to-coarse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!