Location, Location, Location! Well this article isn’t all about location.
Things I will cover in this article:
- Get the location of the users device (via the NETWORK). This will be latitude and longitude.
- Reverse-Geo code information from the first step and get an address
- Send that off to a server via Http GET. (This is typically what you would want to do given a location ;) )
Getting a location
So first off, how do we get the users current latitude and longitude? There are two options (1) We could use the Network (2) Or the GPS. Somehow, getting a location from the network is quite accurate (I tested it a couple times) and it’s fairly fast. Getting a location from the GPS then isn’t too difficult.
So in a default Android application you would want to add the following permission in your AndroidManifest.xml :
This is if you’re using the network, to use the GPS you would need:
I have an
AddressActivity.java and a
main.xml. My view looks like this:
The first button gets my location and the code is below. This is pretty straightforward and the snippet is plagiarized straight from the Android docs here. I have two activity level variables
lon, I store the locations here so I can use them later.
To get a location from the GPS you would just change this line:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Getting an Address
The magic for reverse geo-coding comes from the Geocoder class. You would need the Internet permission in your manifest and this results in an internet call.
I encapsulate all my geocoder stuff into a
GetAddress() function which I call from my
btnAddress. It looks like this:
Send to the Internet
Now typically when you get this far, you want to send this information off to your server somewhere and then do something useful with it. So the last function
postData() sends a latitude and longitude to my server. I made little dummy program on AppHabour in ASP.NET-MVC3. It sends the data via GET through a URL.
No doubt you need the INTERNET permission as I described earlier. The code looks like this:
And there you have it!
Hopefully soon I will use an AsyncTask to wrap up all of this code, so it happens asynchronously.