【发布时间】:2016-05-20 18:39:56
【问题描述】:
我正在为 Android 和 iOS 构建一个应用程序,它可以拍照、检索设备位置并将包发送到服务器进行处理。
要获取设备位置,我知道我需要使用 LocationManager 的 getCurrentLocation 方法之一。但它们在我看来都很相似,所以我选择了一个,但我不确定我选择了正确的一个,因为它在 Android (KitKat) 上效果不佳(我稍后会解释)。
确实,我经历过与最近报道的 [这里] (How to make an immediate reading location using GPS) 相同的怪事,甚至更糟。例如,连接到家庭/办公室 Wifi 的位置(虽然是室内)是准确的。我了解到该设备的结果基于网络。但是,当我在 5 公里(和 40 分钟)外的开阔天空并使用 getCurrentLocation 或 getCurrentLocationAsync 甚至超时执行位置测试时,设备会以 50 m 的精度输出我家/办公室过去的位置。
我还注意到,通常出现在 Android 状态栏中靠近时钟的位置图标没有出现。为了让它看起来,我注意到从谷歌启动地图应用程序会出现位置图标,然后我的应用程序能够找到设备。
这是我用来获取位置的最后一种方法:
`public static final void updateGeolocation (){
Location location = null;
try {
location = LocationManager.getLocationManager().getCurrentLocation();
setLocation(location);
setGeolocationAccuracy(location.getAccuracy() > 0.0f ? location.getAccuracy() : DEFAULT_GEOLOCATION_ACCURACY);
} catch (IOException e) {
setLocation(null);
setGeolocationAccuracy(DEFAULT_GEOLOCATION_ACCURACY);
}
}`
现在这里是我如何通过 timerTask 更新位置:
// On lance la mise à jour périodique de la position de l'appareil
// la tache se lance en dehors de l'EDT
ParametresGeneraux.setCheckTimer(new Timer());
ParametresGeneraux.setCheckTask(new TimerTask(){
@Override
public void run() {
ParametresGeneraux.updateGeolocation();
}
});
ParametresGeneraux.getCheckTimer().schedule(ParametresGeneraux.getCheckTask(), 0, ParametresGeneraux.GEOLOCATION_CHECK_INTERVAL);
注意:关于构建提示,我通过提示 ios.locationUsageDescription 解释了我对 GPS 的需求 我禁用了 android.captureRecord 提示,因为我确实需要它并且不想让用户怀疑我为什么需要捕获记录。
所以我的问题是:
我是否以正确的方式使用 getCurrentLocation 以便我可以责怪我的手机硬件,还是我使用错了?
-
为什么屏幕上部的位置图标只有在我启动 Google 地图而不是我的应用程序时才会出现(好像我的应用程序没有触发位置)。 ?
如果我不使用超时并且该位置需要 10 分钟才能到达怎么办?会发生什么 ?如果我将超时设置为 10 秒并且位置在 10 分钟后到达(例如我在隧道中)会有什么区别?
是否首选使用 LocationListener,尽管它可能仅在设备位置更改时触发?
提前感谢谁能让我更清楚这一点,
编辑:遵循@ShaiAlmog 的建议以使我必须顺利进行所有工作:
- 不要使用上述 updateGeolocation() 方法
- 创建实现 LocationListener 的 GeolocationListener 侦听器并在覆盖的 updateLocation 方法中执行我的工作(见下文)
- 在主类的 init 方法中将 LocationListener 设置为我的 GeolocationListener
现在更新的位置可用,并且位置图标按预期显示。
我的 GeolocationListener 就像下面的代码一样简单:
public class GeolocationListener implements LocationListener{
@Override
public void providerStateChanged(int newState) {
}
/**
* Met à jour les valeur de la position et la précision de la géolocalisation si le service de géoloc est dispo. Sinon met à jour les valeurs avec null pour la position
* et DEFAULT_GEOLOCATION_ACCURACY pour la précision
*/
@Override
public void locationUpdated(Location location) {
// Par défaut
ParametresGeneraux.setLocation(null);
ParametresGeneraux.setGeolocationAccuracy(ParametresGeneraux.DEFAULT_GEOLOCATION_ACCURACY);
/*On met à jour la position et la précision
*/
if (location != null && (location.getStatus() == LocationManager.AVAILABLE)){
ParametresGeneraux.setLocation(location);
if ( location.getAccuracy() > 0.0f ) {
ParametresGeneraux.setGeolocationAccuracy(location.getAccuracy());
}
} // fin de la mise à jour de la position
}
}
问候
【问题讨论】: