In my ongoing quest to write about little known or poorly documented features of Android, I stumbled across something this morning that I feel needs a little bit more exposure, as it frustrated me for quite a while trying to figure it out.
In my ongoing quest to write about little known or poorly documented features of Android, I stumbled across something this morning that I feel needs a little bit more exposure, as it frustrated me for quite a while trying to figure it out.
Here’s something handy I learned with Android the other day.
Lets say you have two activities. The first one, A, has a button that opens up the second activity, B. B, in turn has a button that returns the user to activity A. So, if you were to push the button in activity A, you would end up in activity B and vice versa. Pretty straight forward.
Now, lets say you just pushed the button in activity A, and ended up in activity B. You now want to go back to activity A. Pretty simple, just push the button in B, right? While if we push the button, we do in fact end up looking at activity A again, but it is not, in fact, the same instance of activity A that brought us to B in the first place.
So, lets say your application needs to let the user know when he/she is within, say, 1 mile of a given location. Or, you want to sort a series of locations based on how close to the user the points are in a straight line. How do you go about doing that? One way would be to use the Haversine formula to figure out the distances between two points, considering that Earth is spherical, but that takes math, and who likes doing that?
Thankfully, there is a much simpler way to figure out distances between two points on a map: the distanceTo() method in the Location class. Using this handy little method, we can quickly find out the distance between two locations:
double distance;
Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
LocationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB);
One thing to note is that the distanceTo() method returns the distance in meters, so you will need to do the appropriate calculations if you want your distances in other units.