Google位置服务API是Google Play服务的一部分,是向您的应用添加位置感知功能的首选方式。 它提供了更简单的API,更高的精度,低功耗的地理围栏等等。 如果您当前正在使用android.location API,强烈建议您尽快切换到Google Location Services API。
而是推荐the Google Location Services API ,然后你懂得....emmm........
2.1 直接获取地理信息
使用getLastKnownLocation方法获取:
//获取LocationManager的实例对象 locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE); //获取支持的provider列表 List<String> providers = locationManager.getProviders(true); Location bestLocation = null; //遍历provider列表 for (String provider : providers) { //通过getLastKnowLocation方法来获取 Location l = locationManager.getLastKnownLocation(provider); if (l == null) { continue; } if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) { // Found best last known location: %s", l); bestLocation = l; } } |
这里需要注意的是,为啥通过循环provider来获取,比如有些人会问,我开启了GPS,我想通过GPS来定位,我不是直接getLastKnowLocation(LocationManager.GPS_PROVIDER)就可以了吗?理论上是没问题的,但是大部分时候获取到的都是null , 毕竟GPS本身定位时间也会很久,而且如果在室内就更加GG了。
所以网上经常看到有提问:
当然解决方式也有很多,有些人直接通过while循环,比如一直请求:
while(xxx = null){ xxx = getLastKnowLocation(LocationManager.GPS_PROVIDER); } |
这还不算坑爹,我用了华为和小米手机,小米手机使用这个GPS来获取Location,一下子就获取了。华为我写了while循环,等了很久很久,也还是一直是null。(居然还跟不同牌子手机都有关系)
所以最终我是遍历了provider来获取最佳的地址来解决的,如果获取不到GPS定位,也会有network辅助。
也可以参考相关的链接了解一下:Android 成功 使用GPS获取当前地理位置(解决getLastKnownLocation 返回 null),不过貌似也没有找到百分百直接获取GPS定位获取信息的方式。
2.2 监视位置变化
使用requestLocationUpdates方法来获取。
public void requestLocationUpdates( String provider, long minTime, float minDistance, LocationListener listener) { } |
我们可以看到传入provider,最小更新时间,最小的更新距离,然后就是回调listener。
所以我们重点在于LocationListener:
mLocationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { //比如判断location是否为null,然后根据Location来转换成相关的地址位置信息。 } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { //比如在provider失效了就取消监听 locationManager.removeUpdates(this); } }; |
切记,在某个你需要的条件下,通过removeUpdates()去取消监听,比如你可能在onPause中去取消等。
我们在onLocationChanged方法中获取到了Location对象,就可以去获取相关信息了。
通过Location来获取相关的经纬度:
double latitude = location.getLatitude(); double longitude = location.getLongitude(); |
通过Geocoder来把经纬度转换成相应的Address集合:
Geocoder geocoder = new Geocoder(context); List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); |
最后通过Address对象中的相关属性,拼接出自己想要的相关信息。
address.getCountryName() //国家 address.getPostalCode() //邮编 address.getCountryCode() //国家编码 address.getAdminArea() //省份 address.getSubAdminArea() //二级省份 address.getThoroughfare() //道路 address.getSubLocality() //二级城市 ....... |
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。