Android - 未接收意图服务中的位置对象 - 使用定位服务融合位置Api请求位置更新使用挂起的意图



我正在尝试获取位置,特别是当应用程序在后台使用
"位置服务融合位置 API 请求位置更新 - 使用挂起的意图"。

我在这个待处理的意图中调用一个 IntentService 类,它的工作非常好。那是在每个固定的时间间隔之后,我的意图服务被调用,但这里的问题是我没有在接收的意图中收到"位置"类对象。

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

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

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

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

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

最新更新