Accessing the Location Based Services

To access the LBS service on an Android device, you must have the appropriate permissions. Location-based services cannot be used by an Android application unless it is granted the appropriate <uses-permission> settings configured in the Android manifest file.

The most common permissions used by applications leveraging LBS are android.permission.ACCESS_FINE_LOCATION and android.permission.ACCESS_ COARSE_LOCATION. To use the GPS provider, you use android.permission.ACCESS_FINE_LOCATION.

When you have registered the appropriate permission, you can access the LocationManager class by using the getSystemService() method, as follows:

LocationManager locMgr =

(LocationManager) getSystemService(LOCATION_SERVICE);

The LocationManager class allows you to access the LBS functionality available on the device.

Working with Providers

There may be any number of LBS providers for a device. You can get a list of all providers by calling the getProviders() method of the LocationManager class. You can limit the providers returned to only those that are enabled, or you can provide criteria for returning only providers with certain features (such as fine accuracy). You can also use the getBestProvider() method to return the most appropriate provider for a given set of criteria.

Each of these provider retrieval methods returns a list of names of location providers. The best location provider for given set of criteria can be returned by name, using the getProvider() method. You can use the LocationProvider class to inspect a given provider and see what features it has, such as whether it supports altitude, bearing, and speed information and whether using it may incur a monetary cost to the user.

Getting the Last Known Location

You can retrieve the last known location of the device (as calculated by a specific provider) by using the getLastKnownLocation() method of the LocationManager class. This location may not be current, but it often gives you a good starting point, and this data is returned quickly, whereas trying to get a current satellite fix can often take quite some time.

You need not start the provider to get the last known location; you simply need to request its last known result. The getLastKnownLocation() method returns a Location object:

Location recentLoc =


The Location object can contain a number of interesting pieces of information regarding a location. The information available depends on the abilities of the LBS provider. For example, most providers return latitude and longitude, but not all can calculate altitude. You use the getLatitude() and getLongitude() methods to retrieve the coordinates from the Location object.

0 0

Post a comment