I am implementing a simple app that uses locationmanager to get current latitude and longitude of device. I am using below code:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null){
latti = location.getLatitude();
longi = location.getLongitude();
Toast.makeText(this,"Lat: "+latti+"Lng"+longi,Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this,"null",Toast.LENGTH_LONG).show();
}
The problem is that this code always gives null even though I have turned GPS and have internet connection. However if I first open the google maps application and search for my current location then open my app only then above code shows correct latitude and longitude.
I have used plenty of codes from stackoverflow and other websites but all have same issue. Can anybody help please?