Android provides api to retrieve GPS location information. Based on our application, we will either call the service once to fetch the current coordinates, or set up a recurring event that updates us with the latest gps location coordinates at regular intervals. I have recently built an app that required the current location to be posted on a web server only when a user starts the applciation. So it didn’t matter where he moved to later on, I just needed to report his initial location he was when he started the app. Its a very simple task, hence the code for this should also be very simple.
Here’s what I came up with after a little googling and experimenting on my own.
Include these imports.
Now the code to retrieve the current gps location.
LocationManager locationManager =
LocationManagerHelper lmh = new LocationManagerHelper();
Criteria hdCrit = new Criteria();
mlocProvider = locationManager.getBestProvider(hdCrit, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1000, lmh);
Location currentLocation = locationManager.getLastKnownLocation(mlocProvider);
double currentLatitude = currentLocation.getLatitude();
double currentLongitude = currentLocation.getLongitude();
Note the function requestLocationUpdates. The second paramater (3000) is the time in seconds after which the service will try to fetch the location again. As we need the info only once (when the application first starts), we can set it to a higher value. The third argument is a similar field named as minDistance. Please see the main android reference for LocationManager class here. Finally we should call removeUpdates that will stop handling further activity from the locationManager instance, as we do not need the service anymore.