geofencing

Android Tutorial: Geofence

This is a continuation of the „Adding Google Maps with a MapView“ tutorial. I added the Google API to display maps on a Android App..now i´m going to add geofencing.

You can download the SourceCode on GitHub.

Step 1:  Connect to Google API Client 

For the geofence implementation we need a connection to the Google Api Client. This Client allows us to use the Google Services like Search, Gmail, Translate and so on..

I´m going to create a new class called GeofenceController and implement all the needed methods for our case. Lets begin with starting and stoping the Google API Client..

As you can see we need two callbacks to start the client. One for successfull and one for failer connection. I create them separately.

Maybe you are wondering what that means..

For the connection we need the ApplicationContext. In this case i create a new application class to get access to the context and insert it in the GoogleApiClient.Builder.

Don´t forget to add it in the AndroidManifest

The last thing that left is just to start and stop the client through the MainActivity with the callbacks we created.

If you run and build the app you should be able to see the success connection in the logs.

 

Step 2: Adding Geofence

To add geofence we need to create a new geofence object with the  GeofenceBuilder. This is crux to monitor and trigger the geofence events.

I´m going to do that separately in a class. I also add the method geofence() where we are able to get the new created geofence object. What you need is a id, name, latitude and longitude of the favored location and the radius when the event should be triggered. You can set different transitionTypes for your geofence. In our case i add all 3 types.

Geofence.GEOFENCE_TRANSITION_ENTER = triggered if location entered

Geofence.GEOFENCE_TRANSITION_EXIT = triggered if location leaved

Geofence.GEOFENCE_TRANSITION_DWELL = triggered if location passed for a while. For this event you have to set a LoiteringDelay. 

 

Let´s amplify the GeofenceController with a new method addGeofence(). With this method we create a new geofence and start the GoogleApiClient with our callbacks. In this case i´m going to create a new callback AddGeoConnectionCallBack where i add a new service to trigger the events.

Create a new intent to handle the events. We need the GoogleApiClient and the GeofenceRequest. The Request specifies the list of geofence to be monitored.

 

Adding a new method getAddGeofencingRequest() in GeofenceController..

Create a new IntentService.

Configure AndroidManifest.xml. 

Just add this line googleMap.setMyLocationEnabled(true) into the onMapReady() method. You should be able to see your location. Don´t forget to setup the marker otherwise you have to scroll in the map to your location to see the blue point :-)

Build an run..in the logs you can see that the geofence successfully added with your current location and the event „ENTER“ is fired.

Check out the SourceCode on GitHub

Note: Just tested on API Level 22 and 21

10 comments for “Android Tutorial: Geofence

  1. Francesco
    25. Juni 2016 at 20:13

    Good tutoria mate,

    I have only a question. How can I get the values of latitude and longitugide of my position and save it?
    I need this value because I have to calculate the distance between my position and another place.

    Thank you :)

    • Fil
      25. Juni 2016 at 20:42

      Hi Francesco,

      you can get your position with LocationManager or LocationServices and store it simply with SharedPreferences.

      I hope i could help you..otherwise i can make a post in the next days about that.

      Regards,
      Fil :-)

      • Francesco
        25. Juni 2016 at 23:51

        Thanks a lot for the answer Fil,

        But can you explain how to do this? :)

        • Fil
          26. Juni 2016 at 1:47

          Sure. Here are code samples..

          GPS:
          public class GPSManager extends Service implements LocationListener{

          private Context context;
          boolean isGPSEnabled = false;
          boolean isNetworkEnabled = false;
          Location location;
          double latitude;
          double longitude;
          private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
          private static final long MIN_TIME_BW_UPDATES = 60000;
          protected LocationManager locationManager;

          public GPSManager(Context context) {
          this.context = context;
          getLocation();
          }

          public Location getLocation() {
          try {
          locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
          isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
          isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

          if (isNetworkEnabled) {
          getGeoData(LocationManager.NETWORK_PROVIDER);
          }
          else if (isGPSEnabled && location == null) {
          getGeoData(LocationManager.GPS_PROVIDER);
          }
          else {
          //no gps and network
          }

          } catch (Exception e) {
          e.printStackTrace();
          }

          return location;
          }

          private void getGeoData(String provider){
          locationManager.requestLocationUpdates(provider, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
          if (locationManager != null) {
          location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
          if (location != null) {
          latitude = location.getLatitude();
          longitude = location.getLongitude();
          }
          }
          }

          and SharedPreferences:

          //save float
          SharedPreferences sharedPreferences = App.context.getSharedPreferences(„PREFS“, Context.MODE_PRIVATE);
          SharedPreferences.Editor editor = sharedPreferences.edit();
          editor.putFloat(„latitude“, 12345678);
          editor.apply();
          //get int
          latitude = sharedPreferences.getFloat(„latitude“, 0);

          Regards,
          Fil

          • Francesco
            26. Juni 2016 at 16:05

            Thank you so much Fil :)

            Can you do a tutorial about the SharedPreferences? I think that it could be very interesting for everybody 😉

          • Francesco
            26. Juni 2016 at 18:27

            I HAVE A BIG PROBLEM FIL!

            I can’t share my preferences between the activityes. How can I do? :(

  2. Francesco
    30. Juni 2016 at 16:20

    Fil please, i need this tutorial and on web anybody can’t help me :(

  3. 6. Juli 2017 at 3:21

    Greetings! Very useful advice in this particular article!
    It is the little changes that will make the most significant changes.
    Many thanks for sharing!

  4. 6. Juli 2017 at 23:13

    This is my first time pay a visit at here and
    i am actually pleassant to read all at single place.

  5. 26. Juli 2017 at 12:52

    „I really like your writing style, good info, thanks for posting. “Let every man mind his own business.”

Schreib einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *