【问题标题】:How to retrieve the current geolocation synchronously?如何同步检索当前地理位置?
【发布时间】:2017-03-06 07:48:55
【问题描述】:

由于我们的应用程序的工作方式,我需要同步获取用户的当前位置。我们当前的实现使用com.google.android.gms.location.LocationListener 来接收位置更新。问题是,我需要在尝试第一次调用之前更新位置服务器端,否则用户会得到错误的数据。

LocationServices.FusedLocationApi.getLastLocation() 不适合这个,因为 a)它似乎总是返回 null(无论出于何种原因)和 b)我们已经在服务器端保存了用户最后一个已知位置,因此检索最后一个已知位置并发送它对服务器是多余的。

伪代码

//this is the first call I need to make
webservice.appStart(AppStartBody body);
//then I want to retrieve the current location and send it to the server
webservice.setGeoLocation(getCurrentLocation());
//finally, I retrieve the items on the server based on the location
webservice.getListItems();

我想避免等待第一个位置更新事件的可能性,因为我不知道它会在多长时间内触发,并且我可能不得不让我的用户在加载屏幕中停留很长时间,进而失去他们,因为没有人喜欢等待。

【问题讨论】:

  • 如果获取设备位置需要例如5秒,需要5秒。没有办法解决这个问题。如果您同步接收它,那么您的应用程序(或该特定线程)会卡住 5 秒钟。如果您异步接收它,您可以使用这 5 秒做其他事情。使操作同步并不能解决您的问题。 'getLastLocation()' 可能很容易在开发人员的测试手机上返回 'null',而没有其他应用程序请求该位置。在真正的用户手机上运行 Facebook、Google Now 等可能会更好,但我们当然不能依赖它。
  • "...我们已经在服务器端保存了用户最后一个已知位置,因此检索最后一个已知位置并将其发送到服务器是多余的。" ...除非自从应用程序上次运行以来位置实际发生了变化。那么就不是多余的了。
  • 据我了解,只要有应用程序使用,定位服务只会返回最后一个已知位置。一旦所有应用程序与服务断开连接,它将再次返回 null,这不是不可能的情况。我不想依赖像那样不可靠的东西

标签: android gps android-gps android-fusedlocation


【解决方案1】:

我能够通过将检索位置的过程放在 Rx 可观察对象中来解决这个问题,特别是 Single。调用Single 对象的blockingGet 方法以同步检索位置。然后将其放置在 try catch 块中以执行重试,因为在第一次尝试期间该位置并不总是可用。

(我知道这是一个老问题,但无论如何我都会发布一个答案,以便我可以分享我是如何做到的。很抱歉使用 Kotlin 和 RxJava!但我想每个人都会明白我的要点想法并能够以他们喜欢的方式实现它。我也在使用最新的 Google Location API。)

// Use an executor to prevent blocking the thread where 
// this method will be called. Also, DO NOT call this on 
// the main thread!!!
fun tryRetrieveLocationSync(flc: FusedLocationProviderClient,
          executor: Executor, numOfRetries: Int = 3, 
          retryWaitTime: Long = 500): Location {

  var location: Location
  var i = 1

  while (true) {
    try {
      // Place the method call inside a try catch block
      // because `Single#blockingGet` will throw any exception
      // that was provided to the `Emitter#onError` as an argument.

      location = retrieveLocationSync(flc, executor)
    } catch (e: NoLocationDataException) {
      if (i <= numOfRetries) {
        // The value from the `FusedLocationProviderClient#lastLocation` 
        // task usually becomes available after less than second (tried
        // and tested!!), but it's really up to you.

        SystemClock.sleep(retryWaitTime * i)
        i++
      } else {
        throw e // Give up once all the retries have been used.
      }
    } catch (e: Exception) {
      // Rethrow anything else that was thrown from 
      // the `Single#blockingGet`.

      throw e
    }
  }

  return location
}

private fun retrieveLocationSync(flc: FusedLocationProviderClient, 
          executor: Executor): Location {

  return Single.create<Location> { emitter ->
    val task = flc.lastLocation
    task.addOnCompleteListener(executor, OnCompleteListener { // it ->
      if (it.isSuccessful) {
        if (it.result != null) {
          emitter.onSuccess(it.result)
        } else {
          // There is no location data available probably because
          // the location services has just been enabled, the device
          // has just been turned on, or no other applications has 
          // requested the device's location.
          emitter.onError(NoLocationDataException())
        }
      } else {
        // I haven't encountered any exception here but this is
        // just to make sure everything's catchable.
        emitter.onError(it.exception ?: RuntimeException())
      }
    })
  }.blockingGet()
}

【讨论】:

    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多