klein_gat klein_gat - 1 year ago 96
Android Question

Proper procedure to poll GPS location for enhanced GeofencingApi on Android Studio

I’m no programmer but even so I just endeavoured into ‘mixing’ (from others' samples and instructions) a small android project for an art installation that is to be presented outdoors throughout a local university campus. This app, that will display pop-up windows containing anecdotal narrations of events that occurred at that spot upon crossing it’s respective radial fence within the field , requieres location acquisition that doesn’t rely on data carriers or wi-fi providers since there is no coverage in the area and besides those seem to be quite unstable even when tested in an urban environment with network and wi-fi signals available.

I’m using the official example that comes with the android developer documentation, however I’ve read that due to an over efficient practice, the developers biased the API towards using only cellular data and wi-fi unless GPS_PROVIDER is called into polling it’s output thru locationManager so that once requested by the app, the geofence instance can retrieve the more precise location chiefly from there. But I am stuck as to in which portion of the code to add this pertaining lines whether it be a separate class within the java folder or inside the Mainactivity itself as well as to where else in the structure (aside the manifest in the form of permissions) do i have to reference their existence for it to work coherently.

Any help is welcomed.

Answer Source

From your description I gather that you have several constraints. Let me paraphrase what I understood:

  • You want to deploy a location-aware app on a number of devices for an exhibition / art installation.
  • The devices will have no connectivity (no WiFi, no cellular network) and thus need to work with GPS only.
  • You want to detect when each of the devices enters a predefined zone, namely a fixed radius around a point of interest.

Your question is: What's the best way to do this?

LocationManager vs. Google (Play Services) Location API

First off, it's important to understand that the generally recommended way of obtaining location updates has shifted over the past years, away from a manual but fine-grained setup of location updates via Android's LocationManager (+ DIY fusion logic) towards the more powerful and convenient Google Location APIs.

I take it you are aware of both (and the Geofencing API that is part of the Location APIs) and have ruled out the latter because of the connectivity issue. So let's take a look at how to do it with the LocationManager.

Obtaining Updates with the LocationManager

But I am stuck as to in which portion of the code to add this pertaining lines whether it be a separate class within the java folder or inside the Mainactivity itself as well as to where else in the structure (aside the manifest in the form of permissions) do i have to reference their existence for it to work coherently.

Whether you use the LocationManager from an Activity or elsewhere depends mostly on whether you need location updates in just one Activity or in several.

Case 1: Location only in one Activity

You can safely instantiate, start and stop the manager within the lifecycle of that Activity.

public MyActivity extends Activity implements LocationListener {

    private LocationManager locationManager;

    protected void onCreate(Bundle savedInstanceState) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    protected void onResume() {
        // Request GPS updates every second (careful: high battery drain)
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5, this);

    protected void onPause() {

    public void onLocationChanged(Location location) {
        // Do something with the location

    // Implement other LocationListener interface methods here, handle provider status changes

Case 2: Location in several Activities

A detailed code example would go beyond the scope of this answer, but let me provide a sketch:

  • Create a custom Application class that holds the LocationManager instance and start/stops it with the application lifecycle. I have written a simple utility class that you can use for this (you can read more about it here).
  • The application class could also implement the LocationListener interface, though it's probably cleaner to package that logic into your own class (say, a LocationHelper class) and start and stop that class from your application.
  • Finally, distribute location updates via an event bus (e.g. Green EventBus or Otto), so that any Activity, Fragment or other class can subscribe to those updates without needing to know where those locations come from.

Checking a Geofence

For the sake of simplicity let's assume you're going with just one Activity and one geofence. Then you could check for inclusion/exclusion of the current location in that geofence as follows:

public MyActivity extends Activity implements LocationListener {

    // Define a hard-coded POI and geofence radius
    private static final Location POI_A = new Location("dummy");
    static {
        POI_A.setLongitude(/* POI longitude */);
        POI_A.setLatitude(/* POI latitude */);
    private static final int GEOFENCE_RADIUS = 50; // meters


    public void onLocationChanged(Location location) {
        if (location.distanceTo(POI_A) <= GEOFENCE_RADIUS) {
            // Location is within geofence of point of interest A
        } else {
            // Location is outside the geofence of point of interest A

Remarks / Hints

  • You should use a high update interval for GPS so that your app can react quickly when people enter/leave the geofences in your exhibit. However, this will consume a lot of battery, so be sure to have spare batteries / chargers nearby.

  • Without any connectivity, the devices might take a really long time to find a GPS fix (as there is no chance of using Assisted GPS). If you can provide any kind of connectivity in the exhibit area (a single WiFi hotspot, for example) this could greatly speed up the time it takes for your app to start up and acquire a position, even if you're only using GPS.

  • Since the location readings can jump by a couple meters, you should probably build your geofences with hysteresis (e.g. fire an enter event when the user is closer than 40m, and a leave event when they are farther than 60m) to avoid repeated transitions at the edge of the POI circle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download