I've used the Android tutorial with Geofences which, obviously, doesn't work when app is closed. So, after searching around, I've noticed user b-ryce on SO used BroadcastReceiver so geofences get triggered even if app is not active (link for his SO question).
I just cannot force geofences to trigger when I move outside/inside registered location. Here's my procedure:
/**
* GeoLocation library
*/
mGeoLocation = new GeoLocation(sInstance);
/**
* mReceiver init
*/
mReceiver = new Receiver();
sInstance.registerReceiver(mReceiver, mReceiver.createIntentFilter());
And inside GeoLocation class:
/*
* Create a PendingIntent that triggers an IntentService in your
* app when a geofence transition occurs.
*/
protected PendingIntent getTransitionPendingIntent() {
if (mGeoPendingIntent != null) {
return mGeoPendingIntent;
}
else {
// Create an explicit Intent
// Intent intent = new Intent(mContext,
// ReceiveTransitionsIntentService.class);
Intent intent = new Intent(getClass().getPackage().getName() + ".GEOFENCE_RECEIVE");
/**
* Return the PendingIntent
*/
return PendingIntent.getBroadcast(
mContext,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
Here's how I create new geofence:
Geofence fence = new Geofence.Builder()
.setRequestId(hashCode)
// when entering this geofence
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(
Double.parseDouble(single.getSetting("latitude")),
Double.parseDouble(single.getSetting("longitude")),
Float.parseFloat(single.getSetting("radius")) // radius in meters
)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
mGeofences.add(fence);
Array gets populated and we call AddGeofences method inside Geofence class
mGeoLocation.AddGeofences(mGeofences);
AndroidManifest.xml for reciever class:
<!-- RECEIVER -->
<receiver android:name=".Receiver" >
</receiver>
And the Receiver class should just log when geofence triggers
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("sfen", "Broadcast recieved "+ action +" but not needed.");
}
The problem is, that Geofence are triggering ONLY when I open map inside my app where I pick the locations. Closing the app (running it in background) doesn't trigger anything and geofence transitions don't trigger anything.
Can someone tell me what am I doing wrong?