: Beginning Android

Finding Yourself

Finding Yourself

The obvious thing to do with a location service is to figure out where you are right now.

To do that, you need to get a LocationManager call getSystemService(LOCATION_SERVICE) from your activity or service and cast it to be a LocationManager.

The next step to find out where you are is to get the name of the LocationProvider you want to use. Here, you have two main options:

Ask the user to pick a provider.

Find the best-match provider based on a set of criteria.

If you want the user to pick a provider, calling getProviders() on the LocationManager will give you a List of providers, which you can then present to the user for selection.

Or, you can create and populate a Criteria object, stating the particulars of what you want out of a LocationProvider, such as the following:

setAltitudeRequired() to indicate if you need the current altitude or not

setAccuracy() to set a minimum level of accuracy, in meters, for the position

setCostAllowed() to control if the provider must be free or not (i.e., if it can incur a cost on behalf of the device user)

Given a filled-in Criteria object, call getBestProvider() on your LocationManager, and Android will sift through the criteria and give you the best answer. Note that not all of your criteria may be met all but the monetary-cost criterion might be relaxed if nothing matches.

You are also welcome to hard-wire in a LocationProvider name (e.g., gps), perhaps just for testing purposes.

Once you know the name of the LocationProvider, you can call getLastKnownPosition() to find out where you were recently. Note, however, that recently might be fairly out-of-date (e.g., if the phone was turned off) or even null if there has been no location recorded for that provider yet. On the other hand, getLastKnownPosition() incurs no monetary or power cost, since the provider does not need to be activated to get the value.

These methods return a Location object, which can give you the latitude and longitude of the device in degrees as a Java double. If the particular location provider offers other data, you can get at that as well:

For altitude, hasAltitude() will tell you if there is an altitude value, and getAltitude() will return the altitude in meters.

For bearing (i.e., compass-style direction), hasBearing() will tell you if there is a bearing available, and getBearing() will return it as degrees east of true north.

For speed, hasSpeed() will tell you if the speed is known, and getSpeed() will return the speed in meters per second.

A more likely approach to getting the Location from a LocationProvider, though, is to register for updates, as described in the next section.

: 1.610. /Cache: 3 / 0