1

我正在尝试获取位置,特别是当应用程序在后台使用
LocationServices FusedLocationApi requestLocationUpdate - Using pending intents ”时。

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

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

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

4

2 回答 2

0

经过反复试验,我发现,显然,当您创建 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 中)。所以总结一下:我不知道它为什么会这样,但它确实让我觉得很奇怪,到目前为止我还没有找到任何文件说明它应该这样表现......

于 2017-09-29T14:07:39.283 回答
0

这就是您从意图服务中的意图获取位置的方式 -

LocationResult locationResult = LocationResult.extractResult(intent);
if (locationResult != null) {
    Location location = locationResult.getLastLocation();
}
于 2016-02-18T06:47:16.483 回答