So, I am making use of Geofences in my app. I have tree locations on a GoogleMaps map and all three are geofences.
So far they are successfully built and added to my app but no trigger is activated when I enter the geofence area.
Location permissions are working so I assume it is not a problem from them therefore I am not posting them.
I am following the official tutorial from the android documentation - link
Why is the trigger not working?
Here is my code:
OnCreate()
geofencingClient = LocationServices.getGeofencingClient(this)
GeofencingConstants.BookPlaces_DATA.forEach {
geofenceList.add(Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(it.name)
// Set the circular region of this geofence.
.setCircularRegion(
it.latLng!!.latitude,
it.latLng!!.longitude,
GeofencingConstants.GEOFENCE_RADIUS_IN_METERS
)
// Set the expiration duration of the geofence. This geofence gets automatically
// removed after this period of time.
.setExpirationDuration(GeofencingConstants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
// Set the transition types of interest. Alerts are only generated for these
// transition. We track entry and exit transitions in this sample.
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
// Create the geofence.
.build())
}
Request
private fun getGeofencingRequest(): GeofencingRequest {
return GeofencingRequest.Builder().apply {
setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
addGeofences(geofenceList)
}.build()
}
Intent..does not trigger the receiver
private val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(this, GeofenceBroadcastReceiver::class.java)
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
// addGeofences() and removeGeofences().
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
Add geofences
private fun addGeofencesToClient(){
geofencingClient?.addGeofences(getGeofencingRequest(), geofencePendingIntent)?.run {
addOnSuccessListener {
// Geofences added
// ...
Log.i("added","GEOFENCES ADDED")
Toast.makeText(this@MapsActivity, R.string.geofences_added,
Toast.LENGTH_SHORT)
.show()
}
addOnFailureListener {
// Failed to add geofences
// ...
println(it.localizedMessage)
Log.i("failed","NOT ADDED")
}
}
}
It is actually working. What I needed to do is to open GoogleMaps on the emulator because apparently it needs so to get your location.