Getting location updates in a BroadcastReceiver
suggest changeFirst create a BroadcastReceiver class to handle the incoming Location updates:
public class LocationReceiver extends BroadcastReceiver implements Constants { @Override public void onReceive(Context context, Intent intent) { if (LocationResult.hasResult(intent)) { LocationResult locationResult = LocationResult.extractResult(intent); Location location = locationResult.getLastLocation(); if (location != null) { // Do something with your location } else { Log.d(LocationReceiver.class.getSimpleName(), "*** location object is null ***"); } } } }
Then when you connect to the GoogleApiClient in the onConnected callback:
@Override public void onConnected(Bundle connectionHint) { Intent backgroundIntent = new Intent(this, LocationReceiver.class); mBackgroundPendingIntent = backgroundPendingIntent.getBroadcast(getApplicationContext(), LOCATION_REUEST_CODE, backgroundIntent, PendingIntent.FLAG_CANCEL_CURRENT); mFusedLocationProviderApi.requestLocationUpdates(mLocationClient, mLocationRequest, backgroundPendingIntent); }
Don’t forget to remove the location update intent in the appropriate lifecycle callback:
@Override public void onDestroy() { if (servicesAvailable && mLocationClient != null) { if (mLocationClient.isConnected()) { fusedLocationProviderApi.removeLocationUpdates(mLocationClient, backgroundPendingIntent); // Destroy the current location client mLocationClient = null; } else { mLocationClient.unregisterConnectionCallbacks(this); mLocationClient = null; } } super.onDestroy(); }
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents