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
Francesco 25. Juni 2016
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 — Autor der Seiten
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
Thanks a lot for the answer Fil,
But can you explain how to do this? 🙂
Fil 26. Juni 2016 — Autor der Seiten
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
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
I HAVE A BIG PROBLEM FIL!
I can’t share my preferences between the activityes. How can I do? 🙁
Francesco 30. Juni 2016
Fil please, i need this tutorial and on web anybody can’t help me 🙁
payday loans 6. Juli 2017
Greetings! Very useful advice in this particular article!
It is the little changes that will make the most significant changes.
Many thanks for sharing!
Leesa 6. Juli 2017
This is my first time pay a visit at here and
i am actually pleassant to read all at single place.
dani 26. Juli 2017
„I really like your writing style, good info, thanks for posting. “Let every man mind his own business.”
softbiz 15. August 2017
The way you write, you are really a professional blogger.:.–~
Mina 18. September 2017
You have a great site ^_^
automatic link exchange 22. September 2017
Magnificent site. A lot of helpful information here. I am sending it to some friends ans also sharing in delicious. And of course, thank you in your effort!
pussysaga crack 21. Juni 2018
Some truly wonderful content on this web site , appreciate it for contribution.
LLC Texas 8. Oktober 2018
This post gives clear idea for the new people of blogging, that
in fact how to do blogging.
PHP Script 28. Februar 2019
Yes, really. I join told all above. We can communicate on this theme. Here or in PM.
parasite seo 17. Dezember 2019
My relatives every time say that I am killing my time here at net, however I know I am getting know-how everyday by reading
thes good content.
Typicalcat15 26. Dezember 2019
Very good info. Lucky me I discovered your blog by chance (stumbleupon). I have book marked it for later!
camo phone case 10. November 2020
Thanks for your marvelous posting! I certainly enjoyed reading it, you can be a great author.
I will ensure that I bookmark your blog and may come back
down the road. I want to encourage that you continue your great posts, have a nice weekend!