Download Teach Yourself Android Application Development in 24

Transcript
Using Location-Based Services
245
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 =
locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
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.
Receiving Location Updates
When you need more current information and want to know when the location
changes, you can register for periodic location updates by using the
requestLocationUpdates() method of the LocationManager class. This method
allows an activity to listen to events from a specific provider (for example, the best
provider given your criteria). This frequency of notifications can be adjusted by specifying the minimum time (in milliseconds) and the minimum distance interval (in
meters) between updates.
To receive a notification when the location changes, you should have the interested
activity implement the LocationListener (android.location.LocationListener)
interface. This interface has a number of helpful callback methods, which allow the
activity to react when the provider is enabled and disabled, when its status changes,
and when the location changes.
Resolving the current location can take some time. Therefore, you’ll want to consider putting most LBS calls in a worker thread separate from the main UI thread
(or writing a background service to support your application). We will discuss
threading later in this book.
Watch
Out!