Android testing9 min readUpdated

How to test geofences on Android

A practical way to test geofence transitions without walking around: what the platform guarantees, a test plan, desk-side simulation, and how to read what happened.

A circular geofence drawn on a map grid with a dotted path that enters and leaves the circle, with a marker at each crossing point

To test geofences on Android without walking around, give the device a simulated location, move it across the fence boundary on a route, and read the transitions your receiver logs. Do this with a slow route, a wait inside the fence and a few deliberately bad location fixes, because the platform reports transitions with a delay and from imperfect location data. A single jump to a point inside the circle tests very little.

How do Android geofences actually behave?

A geofence is a latitude, longitude and radius, which together define a circular area. Your app registers it through the GeofencingClient and receives an Intent when something happens, typically in a BroadcastReceiver. The behaviours below come from the official Android geofencing documentation (opens in a new tab).

  • Transitions. GEOFENCE_TRANSITION_ENTER fires when the device enters the fence and GEOFENCE_TRANSITION_EXIT when it leaves. GEOFENCE_TRANSITION_DWELL fires only after the device has stayed inside for a duration you set as the loitering delay. The docs suggest dwell as the way to cut alert spam when someone drives briefly past a fence.
  • Initial trigger. With INITIAL_TRIGGER_ENTER, an enter transition also fires if the device is already inside when you register the fence. INITIAL_TRIGGER_DWELL exists too. This is useful for tests, as you will see below.
  • Radius. For best results the documentation recommends a minimum radius of 100 to 150 meters. Wi-Fi location accuracy is usually 20 to 50 meters, and without Wi-Fi it can degrade to several hundred meters or more.
  • Delay. The service does not poll location constantly. The docs say latency is usually under 2 minutes, about 2 to 3 minutes on average when Android 8.0 background location limits are in effect, and up to 6 minutes if the device has been stationary for a long time. setNotificationResponsiveness trades latency for power.
  • Permissions. The app needs ACCESS_FINE_LOCATION, plus ACCESS_BACKGROUND_LOCATION if it targets Android 10 (API level 29) or higher. On Android 11 and higher the system dialog does not offer "Allow all the time"; the user enables it on a settings page, as described on the background location page (opens in a new tab).
  • Limit. 100 geofences per app, per device user.
  • Re-registration. Google Play services restores geofences after its own upgrade or restart. Your app must register them again after a reboot, a reinstall, cleared app data, cleared Google Play services data, or a GEOFENCE_NOT_AVAILABLE alert.
A dotted path crosses a circular geofence from left to right. Marker 1 sits where it crosses inward (enter), marker 2 inside the circle (dwell after the loitering delay), marker 3 where it crosses outward (exit).
Enter and exit depend on the boundary crossing; dwell also depends on time, so a test route needs a wait inside.

Why are geofences hard to test by hand?

Transitions arrive minutes after the event, so a quick lap round the block proves little. The location the service sees is not the exact position of the phone, and near the edge a small error flips the result. The documentation notes that on most devices the geofence service uses only network location for triggering, which is why a fence smaller than the typical accuracy can behave in ways that look random. And cases such as a rebooted phone or a killed app are awkward to repeat on foot.

A vertical line marks the fence edge. Four location fixes, each with an accuracy circle, fall alternately inside and outside the line while the true position of the phone stays inside.
The phone is stationary, yet fixes 2 and 4 are reported outside: with a fence this small the app can see exit and enter events that nobody caused.

What should a geofence test plan cover?

Each row below is something a real user will eventually do.

Case How to simulate it What to check
Cross inward Start about 2 radii outside, then move through the centre One enter event, with the right geofence ID
Cross outward Start inside, then leave One exit event
Dwell Enter, then wait longer than the loitering delay Dwell fires after the delay, not before
Pass by just outside Travel along a path that stays outside the circle No event of any kind
Move fast Cross the fence at vehicle speed Event arrives; note how late
Poor accuracy at the edge Hold a point near the boundary and raise the reported accuracy Your app copes with repeated enter and exit, or debounces them
App in background Press home, or lock the screen, before crossing Receiver runs and the event is logged
App killed Remove the app from recents, then cross Observe and document what your app does
After reboot Reboot, wait for boot to finish, then cross Fences are registered again by your boot handling
Permission downgraded Change location to "while in use" in settings, then cross App detects the change and tells the user, rather than failing silently

For the last row, the documentation lists background location as required for geofencing but does not describe the exact failure mode, so record what your build does on your devices instead of assuming.

How do I simulate each case from a desk?

You need a source of test locations that the device accepts. Our guide How to test location features in an Android app covers the emulator, adb, test providers and how to select a mock location app, so this guide does not repeat it. What follows is how to use those locations specifically for geofences.

Four steps in a row: register the fence, place a fixed point, move along a route, read the log. An arrow returns from the last step to the second, with a row of settings to vary one at a time: speed, accuracy, jitter, interval.
Change one setting per run; if you change speed and accuracy together you will not know which one broke the transition.

Start with a control test

Before testing your logic, prove that the setup works. Register a fence with INITIAL_TRIGGER_ENTER, put the device at a fixed point inside it, and confirm an enter event arrives. If it does not, the problem is in registration, permissions or the location source, not in your transition handling. Because the docs say most devices use network location for geofences, this step also shows whether your test source reaches the geofence service on that device.

Fixed points, then a route

  1. Set a fixed point well outside the fence, at least two radii from the centre.
  2. Set a fixed point inside, near the centre. Switch between the two to check the enter and exit.
  3. Build a route that starts outside, crosses the boundary, pauses inside and leaves on the other side.
  4. Replay it slowly first, then fast.
  5. Move the route so it passes close to the edge without crossing it.

Worked example with Mock GPS

Mock GPS is our Android app for this kind of test. The features that matter here: choosing a point by address search, coordinates or the map; routes with several stops and waiting times; playback with pause, resume and adjustable speed; joystick movement with adjustable speed; and settings for update interval, reported accuracy and location jitter.

For geofences, that maps like this:

  • Fixed inside and outside points cover crossing inward and outward, and the joystick can nudge the position across the boundary.
  • A route with a stop inside the circle, with a waiting time longer than your loitering delay, covers dwell.
  • Playback speed covers walking pace against vehicle speed.
  • Raising the reported accuracy and turning on jitter, then holding a point near the edge, reproduces the situation in the second figure.

It has limits you should know about. Some apps do not accept simulated locations, and Mock GPS does not hide Android's mock-location flag or guarantee compatibility with other apps. The product information also does not say how the geofence service treats a simulated location on any particular device, so do the control test first.

How do I see what happened?

Log in the receiver, and log the errors as carefully as the transitions. This follows the pattern in the official documentation.

class GeofenceReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val event = GeofencingEvent.fromIntent(intent) ?: return
        if (event.hasError()) {
            val message = GeofenceStatusCodes.getStatusCodeString(event.errorCode)
            Log.e("Geofence", "error ${event.errorCode}: $message")
            return
        }
        val ids = event.triggeringGeofences?.joinToString { it.requestId }
        Log.i("Geofence", "transition=${event.geofenceTransition} ids=$ids")
    }
}

Timestamps let you measure latency; filter with adb logcat -s Geofence. Also attach a failure listener to addGeofences(), since registration itself can fail.

The status codes on the GeofenceStatusCodes reference (opens in a new tab) page that matter most:

Code Meaning
GEOFENCE_NOT_AVAILABLE (1000) The geofence service is not available now; location being off is a common cause. Re-register once it is available again.
GEOFENCE_TOO_MANY_GEOFENCES (1001) More than 100 geofences registered.
GEOFENCE_TOO_MANY_PENDING_INTENTS (1002) More than five distinct PendingIntent objects passed to addGeofences.
GEOFENCE_INSUFFICIENT_LOCATION_PERMISSION (1004) The client lacks the location permission needed.
GEOFENCE_REQUEST_TOO_FREQUENT (1005) Geofences are being added too frequently.

Why does a transition never fire?

The documentation's troubleshooting section for missing enter events lists these reasons, and you can rule them out one by one:

  • Accurate location is not available inside the fence, or the fence is too small.
  • Wi-Fi is off. Wi-Fi scan only mode can still give good network location.
  • There is no reliable network connection inside the fence.
  • You are simply waiting for a delayed alert.

Also check that the fence was registered again after a reboot, that background location was granted, and that you stayed longer than the loitering delay.

What belongs on a geofence release checklist?

  • Every transition type you use is tested, including dwell with a wait longer than the delay, and a pass just outside produces no event.
  • Radius is at least 100 meters, or a smaller value is justified by a test on real hardware.
  • Registration failures and error codes are logged, and GEOFENCE_NOT_AVAILABLE triggers re-registration.
  • Fences are registered again after a reboot, and the count stays under 100 per app.
  • Denied or downgraded background location is detected, and the user is told why it matters.
  • Events are debounced or tolerant of repeated enter and exit near an edge.
  • You have walked or driven the real route at least once on a real device, because simulated tests cannot show how your actual radio environment behaves.

Responsible use

Simulated locations are for apps you build or are authorised to test. Do not use them to mislead other services, to cheat in apps whose rules forbid it, or to interfere with an app you have no permission to test.

QUESTIONS

Frequently asked questions

How do I test a geofence without walking to the location?

Feed the device a simulated location: place a fixed point outside the fence, then inside, and finally replay a route that crosses the boundary. Our guide to testing location features covers the ways to supply those locations.

Why does my geofence trigger late or not at all?

The geofence service does not query location continuously, so Android's documentation says to expect latency, usually under 2 minutes and 2 to 3 minutes on average when background location limits apply. Missing alerts are often caused by a radius that is too small, Wi-Fi being off or no reliable network connection.

What is the smallest geofence radius I should use?

Android's documentation recommends a minimum radius between 100 and 150 meters for best results. It says Wi-Fi location accuracy is usually 20 to 50 meters, and that without Wi-Fi it can degrade to several hundred meters or more.

How many geofences can an app register?

Android's documentation states a limit of 100 geofences per app, per device user. Registering more returns the GEOFENCE_TOO_MANY_GEOFENCES status code.

Do geofences survive a reboot?

No. The documentation says the app must re-register its geofences after a device reboot, after reinstalling the app, after clearing app data or Google Play services data, and after a GEOFENCE_NOT_AVAILABLE alert.

FROM THE STUDIO

Mock GPS

A location testing tool for Android developers and QA teams. Test points, routes and joystick movement with visible session controls.

KEEP READING

More guides.

All guides ↗