Good morning, I am developing an application where I get the user's location through the Android Java LocationListener class, the problem is that sometimes it locates me correctly, other times it locates me more or less 10 or 20 meters from the error (I think this is normal), but the real problem is that sometimes it locates me more than 2 or 3 kilometers away from my real position, I'm thinking that maybe I have something misconfigured, this is my code:
/*Metodo de ubicacion de usuarios, listener de cambio de posicion*/
public void LocListener()
{
buscando=true;
/*Se ejecuta cada vez que hay un cambio en la posicion del usuario*/
final LocationListener milListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
location.getLatitude();
location.getLongitude();
rotacion=location.getBearing();
posicionUsuario = new LatLng(location.getLatitude(),location.getLongitude());
hayUbicacion++;//incrementa en 1 cada vez que se llama a el cambio de posicion
}
/*Se ejecuta cada vez que hay un cambio en la configuracion del gps*/
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
Log.d("debug", "LocationProvider.AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.d("debug", "LocationProvider.OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.d("debug", "LocationProvider.TEMPORARILY_UNAVAILABLE");
break;
}
}
@Override
public void onProviderEnabled(String provider) {
// Este metodo se ejecuta cuando el GPS es activado
// mensaje1.setText("GPS Activado");
}
@Override
public void onProviderDisabled(String provider) {
}
};
/*Verificamos que se tengan los permisos antes de comenzar la busqueda de la ubicacion OBLIGATORIO*/
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, (LocationListener) milListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, (LocationListener) milListener);
/*En 5 segundos se verifica si ya se a leido la posicion del usuario 2 veces
* esto puede ser opcional segun se vea la necesidad de acelerar el proceso
* de busqueda*/
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
/*Si hay coordenadas entonces apagamos el buscador para evitar bug por tareas largas*/
if(hayUbicacion>=1) {
segundaUbicacion=0;//reiniciamos el contador de busquedas para volver a buscar desde el boton de gps
locationManager.removeUpdates(milListener);
locationManager = null;
//Toast.makeText(MainUsuarios.this, "detiene busqueda", Toast.LENGTH_SHORT).show();
buscando=false;
progressUbicacion.setVisibility(View.GONE);
btnPedirTaxi.setVisibility(View.VISIBLE);
animacionCamara();
mtdRastreadorConductoresCercanos();
}
/*Si no han leido las coordenadas las dos veces entonces reiniciamos la busqueda*/
else
{
LocListener();
// Toast.makeText(MainUsuarios.this, "reinicia"+segundaUbicacion, Toast.LENGTH_SHORT).show();
}
}
},3000);//Valor en milisegundos para el reinicio de la busqueda
}
If you know of a solution or know of any code that works correctly, I would appreciate it if you would share it.
I understand the problem you describe, first you must know how providers work:
If you want an exact position , both have a range of error , which one is available is regularly requested, but the most accurate is the GPS one.
To make your measurements more accurate, review the method: requestLocationUpdates()
In your code you are defining:
These are the values that you can modify to obtain a smaller error range, for example in the case of
NETWORK_PROVIDER
,you have defined that every 5 seconds (5000 ms) or every 10 meters to get the geolocation update, in the case of only having WiFi on your device it will only use this provider, the option is to update in less time and in a shorter distance.
As everything has its pros and cons, you should take into account that if you make more requests in a shorter period of time, the battery can run out more quickly.