-1

我正在构建一个需要您当前位置来初始化和显示地图的应用程序。我正在请求使用 更新位置LocationManager.requestLocationUpdates(...),但这似乎只在位置发生变化时给我数据(例如,我移动了 10 英尺)。我也在尝试使用 getLastKnownLocation,但在一些不常见的情况下(例如打开 GPS 并且不移动打开应用程序)这将为我正在使用的所有提供程序返回 null。

每当 getLastKnownLocation 返回 null 时,我的应用程序无法初始化,直到我移动 10 英尺并接收到位置更新。到目前为止,我还没有找到一种方法来轮询我的位置,也没有发现任何暗示当我requestLocationUpdates(...)可以在我订阅的那一刻获得我的第一个数据时,而不是在我等待指定的时间段或移动指定的时间段时距离。

一种方法是requestLocationUpdates(...)在非常小的时间间隔或 0 时间间隔上,将其发送给我当前的位置,然后再次删除 LocationListener,requestLocationUpdates(...)但这次我使用更大的值来避免耗尽电池。

我正在寻找更好的方法来解决这个问题。可能是 getCurrentLocation() 之类的东西,但实际上是任何有效的东西。

4

2 回答 2

3

我正在使用 LocationManager.requestLocationUpdates(...) 请求位置更新,但这似乎只会在位置发生变化时给我数据(例如我移动 10 英尺)。

一旦确定位置,它将为您提供第一次位置更新——无论您是否正在移动。一段时间内继续收听更多更新并不是一个坏主意,因为第一个更新可能不太准确。

我正在寻找更好的方法来解决这个问题。可能是 getCurrentLocation() 之类的东西,但实际上是任何有效的东西。

如果您不想接收持续更新,那么LocationManager.requestSingleUpdate()变体之一呢?

onLocationChanged()这些只会在回调中(或通过)为您提供一个位置更新,仅Intent此而已。无需取消任何侦听器等。调用可能类似于:

locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, Looper.getMainLooper());
于 2016-05-05T18:06:32.830 回答
2

好吧,我认为您只使用 onLocationChanged 方法来完成您的工作。

这样做。

@Override
public void onConnected(@Nullable Bundle bundle) {
  updateUi();   
  }` 

public void updateUi() {
        try {
            mlastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mlastLocation != null) {
                final double latitude = mlastLocation.getLatitude();
                final double longitude = mlastLocation.getLongitude();

               //using this cordinates you can initialize map

                }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }`
于 2016-05-05T16:57:59.820 回答