【问题标题】:Android - Not Receiving Location object in IntentService - using LocationServices FusedLocationApi requestLocationUpdates Using pending IntentsAndroid - 未在 IntentService 中接收位置对象 - 使用 LocationServices FusedLocationApi requestLocationUpdates 使用未决意图
【发布时间】:2016-05-30 04:35:40
【问题描述】:

我正在尝试获取位置,特别是当应用程序在后台使用
LocationServices FusedLocationApi requestLocationUpdate - 使用待定意图”。

我在这个待处理的意图中调用了一个 IntentService 类,它的工作非常好。也就是说,每隔一段时间,我的意图服务就会被调用,但这里的问题是我没有在接收到的意图中接收到“位置”类对象。

我已经尝试检查意图包对象中的每个可用键,还尝试了 LocationResult 类的 hasResult()extractResult() 方法,但没有运气。我没有收到我在服务类的“onHandleIntent()”方法中接收到的位置。

如果有人有这个的工作源代码,请分享。谢谢。

【问题讨论】:

  • 在此处粘贴您的代码 sn-p。

标签: android android-fusedlocation


【解决方案1】:

这就是您从 IntentService 中的 Intent 获取位置的方式 -

LocationResult locationResult = LocationResult.extractResult(intent);
if (locationResult != null) {
    Location location = locationResult.getLastLocation();
}

【讨论】:

    【解决方案2】:

    经过反复试验,我发现,显然,当您创建 PendingIntent 时,您不得将捆绑包添加到 Intent - 如果您这样做,一旦 PendingIntent 交付到您的服务的 onHandleIntent,您将不会获得更新的位置:

    private synchronized PendingIntent getPendingIntent(@NonNull Context context) {
        if (locationReceivedIntent == null) {
            final Intent intent = new Intent(context, LocationService.class);
            intent.setAction(ACTION_LOCATION_RECEIVED);
            /*
            final Bundle bundle = new Bundle();
            bundle.putInt(BUNDLE_REQUESTED_ACTION, LOCATION_UPDATED);
            intent.putExtras(bundle);
            */
            locationReceivedIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
        return locationReceivedIntent;
    }
    

    看到我注释掉的部分了吗?如果我取消注释该部分,我将不会在 onHandleIntent 中收到 Location 对象。如果我将其注释掉(就像我在这里所做的那样),那么它可以正常工作并调用:

            final LocationResult newLocations = LocationResult.extractResult(intent);
            final Location newLocation = newLocations != null ? newLocations.getLastLocation() : null;
    

    在服务的 onHandleIntent 中,我得到了实际位置(存储在 newLocation 中)。所以总结一下:我不知道它为什么会这样,但它确实让我觉得很奇怪,到目前为止,我还没有找到任何文件说明它的行为方式......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多