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.
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