Search code examples
androidlocationmanagerandroid-location

Android location manager getbestlocation return null


I need a little help with some information/help about LocationManager in Android. I'm using this code to get user's specific information depending on his location,but in some situations I get provider=null (I'm not pretty sure when,because that exception was uploaded to our server and I can't reproduce it).

Here is the sample code :

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria crta = new Criteria(); 
crta.setAccuracy(Criteria.ACCURACY_FINE); 
crta.setAltitudeRequired(false); 
crta.setBearingRequired(false); 
crta.setCostAllowed(true); 
crta.setPowerRequirement(Criteria.POWER_LOW); 
String provider = locationManager.getBestProvider(crta, true);
Log.d("","provider : "+provider);
// String provider = LocationManager.GPS_PROVIDER; 
Location location = locationManager.getLastKnownLocation(provider); 
updateWithNewLocation(location); 
locationManager.requestLocationUpdates(provider, 1000, 0, locationListener);

How can I when my provider is null and if there is a way to get the current location and use it?

Thanks in advance!


Solution

  • try this code and dont forget that atleast one of your provider should be enabled

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria crta = new Criteria();
    crta.setAccuracy(Criteria.ACCURACY_FINE);
    crta.setAltitudeRequired(true);
    crta.setBearingRequired(true);
    crta.setCostAllowed(true);
    crta.setPowerRequirement(Criteria.POWER_LOW); 
    String provider = locationManager.getBestProvider(crta, true);
    Log.d("","provider : "+provider);
    // String provider = LocationManager.GPS_PROVIDER; 
    locationManager.requestLocationUpdates(provider, 1000, 0, locationListener);
    Location location = locationManager.getLastKnownLocation(provider); 
    //updateWithNewLocation(location);