I am developing an application that is highly dependent on user location and geo fencing. I am trying to get the user location first and based on that further operations are carried out. Everything is working fine except for the fact that, some times I am getting wrong location values and unless and until I restart the app and in some cases, restart the phone, I don't get the correct value. I will post my Location Api codes below. If any changes required, please do let me know.
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
buildGoogleApiClient();
if (!statusOfGPS) {
displayPromptForEnablingGPS(this);
} else {
permissionAndLocationAccess();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Update location every second
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
} else {
ProgressUtil.hideProgressDialog(prgd_progressDialog);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();
Log.e("Lat and Lng", "onconn");
if (!String.valueOf(lat).equals("0.0")) {
latitudeVal = mLastLocation.getLatitude();
longitudeVal = mLastLocation.getLongitude();
sendLatLong(latitudeVal, longitudeVal);
Log.d("Lat and Lng", "in last loc");
Log.d("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);
new AsyncCaller().execute();
}
}
}
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
Log.e("Lat and Lng", "onchanged");
if (!String.valueOf(lat).equals("0.0")) {
latitudeVal = location.getLatitude();
longitudeVal = location.getLongitude();
ProgressUtil.hideProgressDialog(prgd_progressDialog);
Log.e("Lat and Lng", "onchanged0");
Log.e("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);