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();
} 
\$\endgroup\$
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) {}
      };
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.