【问题标题】:Android: Get recent location only, not getLastKnownLocation?Android:仅获取最近的位置,而不是 getLastKnownLocation?
【发布时间】:2013-07-09 13:04:43
【问题描述】:

我正在开发一个 Android 应用程序,其中当前和精确的位置是关键。检测到 GPS 定位后,它会移动到下一个活动。

问题是我在户外对其进行了测试,发现有时它只是使用了之前修复的位置。

所以我在问什么;除了 getLastKnownLocation 之外,还有其他逻辑可以从 LocationManager 获取位置吗?我还没有找到一个看起来不像的例子

    Location location = locationManager.getLastKnownLocation(provider);

谢谢!

【问题讨论】:

    标签: android gps location


    【解决方案1】:

    这是来自official guide 的示例代码(稍作修改):

    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
             makeUseOfNewLocation(location);
        }
    
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}
      };
    
    // Register the listener with the Location Manager to receive location updates
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    

    在这里,您只需从 GPS 请求更新,一旦收到位置,您就会收到回拨电话。

    【讨论】:

    • 这是为我做的!当然,就我而言,在它更改之前我没有或不需要位置。如果我从“onLocationChanged”调用我的下一个方法,我什至不需要听 GPS 定位。谢谢!
    • 我做了同样的代码..但是 onLocationChanged() 从来没有被调用过..我不知道是什么问题
    【解决方案2】:

    您可以使用LocationListener,然后通过您自己的侦听器实现调用locationManager.requestLocationUpdates()

    【讨论】:

      【解决方案3】:

      Google 发布了新的 Location API,查看此链接https://developer.android.com/training/location/index.html

      对于你的问题,你需要实现位置更新回调来获取当前位置。 https://developer.android.com/training/location/receive-location-updates.html

      【讨论】:

      • 我已经测试了新的Location API,您不再需要指定位置提供者来获取位置更新。 LocationClient 会帮您获取位置更新(就像在 iOS 中一样)。在新的 API 中,您只需要使用 LocationRequest 设置服务参数,如更新间隔、位置准确性。然后让LocaitonClient检索位置更新。
      猜你喜欢
      • 2013-05-30
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 2012-11-15
      • 2020-11-06
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多