Saturday, November 16, 2013

Using android.location for position fixing, distance calculation, proximity alert and others ...

A lot of fun stuff can be done using android.location API ... as simple as calculating distance between two longitude/latitude pairs or as complex as automatically execute task when you are entering or leaving a proximity.

Note: Add the user permission "android.permission.ACCESS_FINE_LOCATION" to AnroidManifest.xml before trying the examples.

To reference the default LocationManager, in a context (e.g. Activity class instance)

LocationManager aLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);


The default LocationManager has two Location Providers, named as "network" and "gps". Depending on the phone's hardware and owner setting, they might be disabled. A list of all providers can be retrieved by ...
aLocationManager.getAllProviders()

Find the best Location Provider
Which provider to use if there are more than one ? You can use the Criteria object to find the best provider, criteria such as cost you the least money (or zero), use the least power, ... says we want to stress on accuracy.

Criteria c=new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
String providerName=lm.getBestProvider(c,true);

The true in the argument has the function to return ONLY enabled provider.

Calculating the distance between two locations with Location class.
e.g.
Location destination=new Location(providerName);
destination.setLatitude(...);
destination.setLongitude(...);
Location source= // ....
source.distanceTo(destination);

Find your last know location
Location aLocation=aLocationManager.getLastKnownLocation(providerName);

Fire Activity on Proximity Alert
Here is the interesting part, says you already created an Activity (e.g. DoSomethingActivity). Now, the DoSomethingActivity is registered to the LocationManager for it's auto start once you are entering or leaving the proximity.

Intent anIntent=new Intent(this,SendSMSActivity.class);
PendingIntent operation=PendingIntent.getActivity(this,0,anIntent, Intent.FLAG_GRANT_READ_URI_PERMISSION);
aLocationManager.addProximityAlert(destination.getLatitude(), destination.getLongitude(), 1000, -1, operation);

Note:
The 1000 is the radius from the destination to the trigger boundary (in meters). The alert fired when you are entering/exiting this radius boundary.
The -1 means this alert never expire or else you can pass a expiration time.