1
\$\begingroup\$

I am trying to get user's current location base on the accuracy and less battery consumption.

Please review my code to help determine if I am going in right direction.

Location location = null;
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_
try {
 String provider = locationManager.getBestProvider(criteria, false);
 locationManager.requestLocationUpdates(provider, 2000, 5,locationListener);
 location = locationManager.getLastKnownLocation(provider);
 lati = Double.toString(location.getLatitude());
 longi = Double.toString(location.getLongitude());
} catch (Exception ex) {
 ex.printStackTrace();
} 
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 6, 2012 at 9:05
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

The last know location could be null. So you need a further check for this, then ask for a quick update:

 if(location == null){
 String provider = locationManager.getBestProvider(criteria, true);
 if (provider != null){
 locationManager.requestLocationUpdates(provider, 0, 0, singeUpdateListener, context.getMainLooper()); 
 }else {
 Log.e("TAG", No location set"); 
 }
 }

class variable:

protected LocationListener singeUpdateListener = new LocationListener() {
 public void onLocationChanged(Location location) {
 String lati = Double.toString(location.getLatitude());
 String longi = Double.toString(location.getLongitude());
 locationManager.removeUpdates(singeUpdateListener);
 }
 public void onStatusChanged(String provider, int status, Bundle extras) {}
 public void onProviderEnabled(String provider) {}
 public void onProviderDisabled(String provider) {}
 };
answered Jul 5, 2012 at 7:45
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.