1

I am trying to fetch locations, specially when app is in background using
"LocationServices FusedLocationApi requestLocationUpdate - Using pending intents".

I am calling an IntentService class in this pending intent and its working just perfectly fine. That is after every regular intervals, my intent service is getting called, but here issue is I am not receiving "Location" class object in the received intent.

I have tried check every available key in intent bundle object, also tried the LocationResult class's hasResult() and extractResult() methods also, but no luck. I am not receiving the location in the intent that i am receiving in "onHandleIntent()" method of my service class.

If someone has working source code of this, please share. Thank you.

Sandeep
  • 1,504
  • 7
  • 22
  • 32
Aashish
  • 81
  • 2
  • 5

2 Answers2

0

This is how you fetch the location from the intent in your intentservice -

LocationResult locationResult = LocationResult.extractResult(intent);
if (locationResult != null) {
    Location location = locationResult.getLastLocation();
}
Jyotman Singh
  • 10,792
  • 8
  • 39
  • 55
0

After trial and error I found out, that apparently when you create the PendingIntent you MUST NOT add a bundle to the Intent - if you do you won't get the updated Location once the PendingIntent is delivered to your Service's 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;
}

See the part I commented out? If I uncomment that part I will not receive the Location object in onHandleIntent. If I comment it out (like I did here) then it works fine and calling:

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

in onHandleIntent of the Service gets me the actual location (stored in newLocation). So to sum it up: I don't know why it behaves like that but it does strike me as very odd and so far I did not manage to find any documentation stating, that it is meant to behave this way...

AgentKnopf
  • 4,295
  • 7
  • 45
  • 81