Login     Sign Up
Tugadar Networking Community (@admin)
7 months ago
35 Views

In the following example, “Where Am I?” is enhanced to track your current location by listening for location changes. Updates are restricted to one every 2 seconds, and only when movement of more than 10 meters has been detected.

Rather than explicitly selecting the GPS provider, in this example, you’ll create a set of Criteria and let Android choose the best provider available.

Start by opening the WhereAmI Activity in the WhereAmI project. Update the onCreate method to find the best Location Provider that features high accuracy and draws as little power as possible.

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

LocationManager locationManager;

String context = Context.LOCATION_SERVICE;

locationManager = (LocationManager)getSystemService(context);

Criteria criteria = new Criteria();

criteria.setAccuracy(Criteria.ACCURACY_FINE);

criteria.setAltitudeRequired(false);

criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW);

String provider = locationManager.getBestProvider(criteria, true);

Location location = locationManager.getLastKnownLocation(provider);

updateWithNewLocation(location);}

Create a new LocationListener instance variable that fires the existing updateWithNewLocation method whenever a location change is detected.

private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) {

updateWithNewLocation(location);

}

public void onProviderDisabled(String provider){ updateWithNewLocation(null);

}

public void onProviderEnabled(String provider){ } public void onStatusChanged(String provider, int status,

Bundle extras){ }

};

Return to onCreate and execute requestLocationUpdates, passing in the new Location Listener object. It should listen for location changes every 2 seconds but fire only when it detects movement of more than 10 meters.

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

LocationManager locationManager;

String context = Context.LOCATION_SERVICE;

locationManager = (LocationManager)getSystemService(context);

Criteria criteria = new Criteria();

criteria.setAccuracy(Criteria.ACCURACY_FINE);

criteria.setAltitudeRequired(false);

criteria.setBearingRequired(false);

criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);

String provider = locationManager.getBestProvider(criteria, true);

Location location = locationManager.getLastKnownLocation(provider);

updateWithNewLocation(location);

locationManager.requestLocationUpdates(provider, 2000, 10,

locationListener);

}

If you run the application and start changing the device location, you will see the Text View update accordingly.