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