0

我试图获取位置并且代码有效,但它无法正常工作。这是我的代码

    // Get the location manager
    LocationManager locationManager = (LocationManager)                 
    getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    try {
        lat =  (int)Math.round((location.getLatitude () * 1e6) ) ;
        lon =   (int)Math.round((location.getLongitude() * 1e6) ) ;
    }
    catch (NullPointerException e){
        lat = -1;
        lon = -1;
    }

问题是当我使用foursqure 或facebook 时,他们直接获取位置,但我的应用程序返回-1,-1(有时),有时它会准确找到位置。可能是什么问题,或者我该如何改进以更好地获得当前位置?谢谢

4

2 回答 2

1

您应该实现 LocationListerner 并请求位置更新。获得修复后,您可以删除位置更新。您可以在http://developer.android.com/reference/android/location/LocationListener.html阅读更多信息

于 2013-04-22T00:05:54.177 回答
0

对 getLastKnownLocation 的调用有时会返回 null,如Andorid 文档中所指定。所以有时该代码确实会产生 lat=lon=-1。此外,getBestProvider 是一种确定最能满足给定标准的提供者的方法。由于您没有指定任何标准,因此合乎逻辑的结论是所有提供者都同样出色,因此结果可能是随机的。最后,请注意 lat=-1 和 lon=-1 是一个有效的位置,所以通常它不是标记错误的好方法。

正如此处另一个答案中所建议的那样,您应该实施http://developer.android.com/reference/android/location/LocationListener.html。然后,您遇到了使用哪些提供程序的问题。我的方法是全部使用它们并使用一个简单的卡尔曼滤波器来处理不同供应商在不同时间具有不同准确度的事实。我在这里发布了用于此的简单卡尔曼滤波器平滑 GPS 数据

于 2013-04-22T07:18:47.327 回答