I am trying to get the current location of the user either by GPS or location provider but every solution I have tried (many from stacksoverflow and google, youtube as well) gives a null as latitude and longitude.
Here is the code I am using
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
double lat = 0;
double lng = 0;
provider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
Toast.makeText(this,"Location"+lat+" "+lng+" ",Toast.LENGTH_LONG).show();
}else
Toast.makeText(this,"Location"+lat+" "+lng+" ",Toast.LENGTH_LONG).show();
The above code always gives 0.0 and 0.0 as lat and long.
I have also included the permissions in Android Manifest :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Any suggestions please?
Working function that checks GPS , Network and LastKnownLocation.. my Suggestion : First use LastKnownLocation then Netowrk and last Resort as GPS.. less Battery usage.
Location results return to the Listeners.