Search code examples
androidmapsbroadcastreceivergeofencing

GeoFencing: BroadcastReceiver fails to trigger


I have tried to run this application from android developer: https://developer.android.com/codelabs/advanced-android-kotlin-training-geofencing?authuser=2#0

The geofences are being added, but nothing gets triggered. i have tried to check this page: https://simpleinout.helpscoutdocs.com/article/232-my-geofences-arent-working-android But my phone seems to be ok...

How can the broadcast not get triggered when i get a log that "geofence is added"??. Is there something wrong with my emulator, Intent or broadcastReceiver??

BroadcastReceiver:

class GeofenceBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == ACTION_GEOFENCE_EVENT) {
            val geofencingEvent = GeofencingEvent.fromIntent(intent)

            if (geofencingEvent.h

Intent:

private val geofencePendingIntent: PendingIntent by lazy {
        val intent = Intent(this, GeofenceBroadcastReceiver::class.java)
        intent.action = ACTION_GEOFENCE_EVENT
        PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    }

add Geofencing:

addOnCompleteListener {
                // Add the new geofence request with the new geofence
                geofencingClient.addGeofences(geofencingRequest, geofencePendingIntent)?.run {
                    addOnSuccessListener {
                        // Geofences added.

Also the location ACCESS_BACKGROUND_LOCATION and ACCESS_FINE_LOCATION Are "always allowed"


Solution

  • Finally figured it out. There was nothing with the code. It doesnt work to test on emulator (at least not for me, not by clicking settings and change location that way)

    The thing that worked for me was testing on a real device:

    • Go to Developer settings and enable mock location
    • download Lockito from appstore.
    • go back to developer settings (mock location) and set the app as "lockito".
    • Set whatever route you want in lockito and click play.