文档详情

【android开发wiki】进阶篇making your app location aware(二):获取当前位置—obtaining the current location.pdf

发布:2016-03-08约5.01千字共5页下载文档
文本预览下载声明
eoe 移动开发者社区 / 原文链接: /training/basics/location/currentlocation.html 通过 LocationManager 设置好你的应用之后,你就可以获取位置数据更新了。 设置位置监听 LocationManager 类拥许多方法用于接受位置数据更新,在它里面最简单的形式,注册一 个时间监听,用于识别来自位置数据更新的位置管理,以及设置最小时间和间隔距离。随着 时间和位置间隔的更新,回调函数onLocationChanged()会被调用。 在下边的代码中, 每隔至少十秒或者距离移动了十米,位置监听函数将要被调用。另外一个通知应用改变状态 的回调函数来自位置提供者。 1. private final LocationListener listener = new LocationListener () { 2. 3. @Override 4. public void onLocationChanged (Location location) { 5. // A new location update is received. Do something useful with it. In this case, 6. // were sending the update to a handler which then updates the UI wi th the new 7. // location. 8. Message.obtain (mHandler, 9. UPDATE_LATLNG, 10. location.getLatitude () + , + 11. location.getLongitude()).sendToTarget(); 12. 13. ... 14. } 15. ... 16. }; 17. eoe 移动开发者社区 / 18. mLocationManager.requestLocationUpdates (LocationManager.GPS_PROVIDER, 19. 10000, // 10-second interval. 20. 10, // 10 meters. 21. listener); 处理多元位置更新 通常来说,使用GPS 的位置提供者要比基于网络的位置提供者耗费更多的时间。如果你尽 可能快的更新位置数据以及你想让更精确的更新数据变得可能,常见的方法就是注册GPS 和网络提供者两种方式的监听器。在onLocationChanged()回调函数里,你将接收来自多 个位置提供的的信息,包含带有不同时间戳和不同等级的信息。你需要通过逻辑处理来消除 歧义信息以及更新最新数据。下边的代码片段演示了这段逻辑。 1. private static final int TWO_MINUTES = 1000 * 60 * 2; 2. 3. /* * Determines whether one Location reading is better than the current Loca tion fix 4. * @param location The new Location that you want to evaluate 5. * @param currentBestLocation The current Location fix, to which you want to compare the new one 6. * / 7. protected boolean isBetterLocation(Location location, Location currentBestLoc
显示全部
相似文档