: Beginning Android

On the Move

On the Move

Not all location providers are necessarily immediately responsive. GPS, for example, requires activating a radio and getting a fix from the satellites before you get a location. That is why Android does not offer a getMeMyCurrentLocationNow() method. Combine that with the fact that your users may well want their movements to be reflected in your application, and you are probably best off registering for location updates and using that as your means of getting the current location.

The Weather and WeatherPlus sample applications (available in the Source Code area athttp://apress.com) show how to register for updates call requestLocationUpdates() on your LocationManager instance. This takes four parameters:

1.The name of the location provider you wish to use

2.How long, in milliseconds, must have elapsed before we might get a location update

3.How far, in meters, the device must have moved before we might get a location update

4.A LocationListener that will be notified of key location-related events, as shown in the following code:

LocationListener onLocationChange =newLocationListener() {
public voidonLocationChanged(Location location) {
updateForecast(location);
}
public voidonProviderDisabled(String provider) {
// required for interface, not used
}
public voidonProviderEnabled(String provider) {
// required for interface, not used
}
public voidonStatusChanged(String provider, int status,
Bundle extras) {
// required for interface, not used
}
};

Here, all we do is call updateForecast() with the Location supplied to the onLocationChanged() callback method. The updateForecast() implementation, as shown in Chapter 30, builds a Web page with the current forecast for the location and sends a broadcast so the activity knows an update is available.

When you no longer need the updates, call removeUpdates() with the LocationListener you registered.


: 0.564. /Cache: 3 / 0