Now that you have seen how the sensor manager works, we
can look at the Location API, another system service provided by Android.
Just like sensors, the Location API is supported via the Location
manager. And just like sensors, we get the Location manager via a
Once we have access to the Location service, we need to register a Location listener with it so the service can call back when there’s a change in location. Again, we’ll do this by implementing a Location listener interface.
If you recall from Common Steps in Using System Services, processing GPS and other location
updates can be very taxing for the battery. To minimize the battery consumption, we want to
listen to location updates only while in the running state. To do that,
we’ll register for the updates in
onResume() and unregister in
onPause(), taking advantage of the activity
This example illustrates how to use location-based
services in Android. First, we use
LocationManager to figure out our current
location based on the resources in the environment available to the
device, such as GPS or a wireless network. Second, we use
Geocoder to convert
this location to an address.
The layout for this
example is trivial, as you can see in Example 13-3.
Our resource file provides a
TextView widget for the title and another
TextView widget for the output.
Since the output could be longer than the screen size, we wrap the
output in a