0

How can I send a PendingIntent with a LocationResult?

I wanted to use same PendingIntent I setup for receiving location changes to also receive the last location.

See the last lines in the code:

// Create pending intent for a service which received location changes
Intent locationIntent = new Intent(getApplicationContext(), LocationIntentService.class);
PendingIntent pendingIntent = PendingIntent.getService(
        getApplicationContext(),
        0,
        locationIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
    );

// Start listening to location changes
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, pendingIntent);

// Get last location
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

// Send last location
if(lastLocation != null) {
   // How to send it to the pending intent?
   // Result result = LocationResult.create( ... )
   // pendingIntent.send(result)
}
Don Box
  • 3,166
  • 3
  • 26
  • 55
  • You need to find out what extras are contained in an `Intent` from the `FusedLocationApi`. Then you can "simulate" that yourself by adding the same extras. – David Wasser May 08 '17 at 14:17
  • Thanks. Correct, the extras key is FusedLocationProviderApi.KEY_LOCATION_CHANGED but it has been deprecated for some reason. I see `LocationResult` has `hasResult(intent)` and `extractResults(intent)` to read from intent, but I can't see the other way around, how to set a `LocationResult` to intent extras. I see there's a `writeToParcel` but no idea how that can work – Don Box May 08 '17 at 17:48
  • You should add debug logging and dump the `Intent` that you get from `FusedLocationApi`, then I can help you simulate it. – David Wasser May 09 '17 at 06:02

1 Answers1

0

Inspecting the code for LocationResult.extractResult(intent) it is possible to see that LocationResult is nothing more than a Parcelable extra inserted in the Intent with a specific Id. The following Kotlin function inserts a List<Location> in a given Intent as a LocationResult

private const val EXTRA_LOCATION_RESULT = "com.google.android.gms.location.EXTRA_LOCATION_RESULT"

@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun insertResult(intent: Intent, locations: List<Location>) {
    val result = LocationResult.create(locations)
    intent.putExtra(EXTRA_LOCATION_RESULT, result)
}

Note: FusedLocationApi has been deprecated and FusedLocationProviderClient should be used instead. I have applied the solution above to unit test the BroadcastReceiver receiving updates from FusedLocationProviderClient

Lorenzo Petroli
  • 458
  • 6
  • 14