Login     Sign Up
Tugadar (@admin)
16 days ago
12 Views

Most location-sensitive applications will need to be reactive to user movement. Simply polling the Location Manager will not force it to get new updates from the Location Providers.

Use the requestLocationUpdates method to get updates whenever the current location changes, using a LocationListener. Location Listeners also contain hooks for changes in a provider’s status and availability.

The requestLocationUpdates method accepts either a specific Location Provider name or a set of Criteria to determine the provider to use.

To optimize efficiency and minimize cost and power use, you can also specify the minimum time and the minimum distance between location change updates.

The following snippet shows the skeleton code for requesting regular updates based on a minimum time and distance.

String provider = LocationManager.GPS_PROVIDER;

int t = 5000; // milliseconds

int distance = 5; // meters

LocationListener myLocationListener = new LocationListener() {

public void onLocationChanged(Location location) { // Update application based on new location.

}

public void onProviderDisabled(String provider){ // Update application if provider disabled.

}

public void onProviderEnabled(String provider){ // Update application if provider enabled.

}

public void onStatusChanged(String provider, int status, Bundle extras){

// Update application if provider hardware status changed.

}

};

locationManager.requestLocationUpdates(provider, t, distance, myLocationListener);

When the minimum time and distance values are exceeded, the attached Location Listener will execute its onLocationChanged event.

You can request multiple location updates pointing to different Location Listeners and using different minimum thresholds. A common design pattern is to create a single listener for your application that broadcasts Intents to notify other components of location changes. This centralizes your listeners and ensures that the Location Provider hardware is used as efficiently as possible.

To stop location updates, call removeUpdates, as shown below. Pass in the Location Listener instance you no longer want to have triggered.

locationManager.removeUpdates(myLocationListener);

Most GPS hardware incurs significant power cost. To minimize this, you should disable updates whenever possible in your application, specifically when location changes are being used to update an Activity’s User Interface. You can improve performance further by extending the minimum time between updates as long as possible.