The busy coders guide to android development feb 2009

Page 345

Accessing Location-Based Services

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

setAltitudeRequired()

not •

setAccuracy()

to indicate if you need the current altitude or

to set a minimum level of accuracy, in meters, for the

position •

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

Given a filled-in Critieria 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 will be met – all but the monetary cost criterion might be relaxed if nothing matches. Once you know the name of the LocationProvider, you can call getCurrentLocation() to turn on the location provider and get an up-to-date fix, or you can call getLastKnownPosition() to find out where you were recently. Note, however, that "recently" might be fairly out of date (e.g., phone was turned off). 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.

324

This document is licensed for Cheng Po-wen's exclusive use by CommonsWare, LLC


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.