Книга: 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 at http://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 = new LocationListener() {
 public void onLocationChanged(Location location) {
  updateForecast(location);
 }
 public void onProviderDisabled(String provider) {
  // required for interface, not used
 }
 public void onProviderEnabled(String provider) {
  // required for interface, not used
 }
 public void onStatusChanged(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.908. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз