I am trying get a Geofence
trigger to a BroadcastReceiver
and the BroadcastReceiver
has the code to read the data from the intent and act on the data sent in intent. My BroadCastReceiver
is GeoLocationBroadCastReceiver
. I am invoking this code when my activity is opened and the app is in background.
public PendingIntent getPendingIntent(Context context){
Intent i = new Intent(context, GeoLocationBroadCastReceiver.class);
return PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
}
This PendingIntent
is passed to the addGeofences method along with the GeofencingRequest.Builder
(this data is returned in the addGeoFence method).
GeofencingClient client = LocationServices.getGeofencingClient(context);
client.addGeofences(addGeoFence(100, lat, long, true), getPendingIntent(context))
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.e(TAG,"Added from location geofence");
}
});
When I invoke the above code the geofence is added successfully.
Receiver declaration in Manifest.xml file:
<receiver
android:name=".LocationMagic.GeoLocationBroadCastReceiver"
android:enabled="true"
android:exported="true"/>
The problem: I am not getting broadcast and the receiver is not called. I see the google suggested approach is to use the broadcast to overcome the background limitations with services. I know the Broadcast limitations as well(whitelisted and blacklisted). But as per google codelabs the suggested approach is to use broadcast. Google code labs link here.
From google codelabs:
Apps targeting O are further subject to limits on services started in the background. For this reason, apps targeting O should not use PendingIntent.getService() when requesting location updates. Instead, they should use PendingIntent.getBroadcast().