2010-08-10 9 views
8

He configurado el LocationManager para obtener la ubicación actual de cada 2 minutos:LocationManager llamando a la ubicación ¿Cambió con demasiada frecuencia?

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 0, this); 

Esto funciona bien y onLocationChanged se llama cada 2 minutos como se esperaba. Sin embargo, parece que se está llamando varias veces en un intervalo de 10-40 (una cantidad aleatoria) de segundo tramo cada 2 minutos. Me conecto cada localización recibida en el onLocationChanged así que aquí están algunas muestras para tener una idea de lo que está pasando:

En 17:30

GPS 32.0 50.66318929195404 10.735434293746948 0.0 2010.08.07 17:30:10 
GPS 32.0 50.66315710544586 10.735423564910889 0.0 2010.08.07 17:30:14 
GPS 32.0 50.66314101219177 10.735418200492859 0.0 2010.08.07 17:30:17 
GPS 32.0 50.66314101219177 10.735418200492859 0.0 2010.08.07 17:30:20 
GPS 24.0 50.66313564777374 10.735418200492859 0.5 2010.08.07 17:30:24 
GPS 32.0 50.663098096847534 10.735573768615723 0.0 2010.08.07 17:30:28   
GPS 32.0 50.663065910339355 10.735611319541931 0.0 2010.08.07 17:30:31 

Luego llego no hay más actualizaciones durante 2 minutos.

En 17:32

GPS 32.0 50.661821365356445 10.737022161483765 1.0 2010.08.07 17:32:39 
GPS 16.0 50.66170871257782 10.737043619155884 1.8200275 2010.08.07 17:32:45 
GPS 24.0 50.661579966545105 10.737027525901794 1.25 2010.08.07 17:32:50 
GPS 16.0 50.66150486469269 10.73712408542633 1.0 2010.08.07 17:32:55 
GPS 12.0 50.661579966545105 10.73715090751648 0.9013878 2010.08.07 17:33:01 
GPS 24.0 50.66139221191406 10.737038254737854 1.5811388 2010.08.07 17:33:06 
GPS 16.0 50.66141366958618 10.737301111221313 0.70710677 2010.08.07 17:33:12 
GPS 16.0 50.66141366958618 10.737301111221313 0.70710677 2010.08.07 17:33:12 
GPS 24.0 50.661311745643616 10.737070441246033 1.118034 2010.08.07 17:33:16 
GPS 16.0 50.66122591495514 10.737177729606628 1.118034 2010.08.07 17:33:22 
GPS 12.0 50.66124200820923 10.737220644950867 1.3462912 2010.08.07 17:33:26 
GPS 12.0 50.661311745643616 10.737268924713135 3.6055512 2010.08.07 17:33:25 

Y así sucesivamente ... y luego otra serie de cambios 2 minutos más tarde a las 17:35.

¿Es este el comportamiento estándar? Esperaba obtener solo una ubicación cada 2 minutos, y el intervalo de tiempo en el que me da actualizaciones de ubicación parece bastante aleatorio. Idealmente, preferiría obtener solo una ubicación ... ¿hay alguna manera de hacer esto?

Respuesta

13

De la documentación de requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener) concering la minTime parámetros:.

"el intervalo de tiempo mínimo para las notificaciones, en milisegundos Este campo sólo se utiliza como una pista para conservar la energía y el tiempo real entre las actualizaciones de ubicación puede ser mayor o menor que este valor ".

Así que la respuesta a sus preguntas, sí, este es el comportamiento estándar y, no, no puede cambiar esto.

Si esto es un problema para usted, puede ignorar las llamadas al método de devolución de llamada si una cierta cantidad de tiempo no ha transcurrido.

+0

thaaannnkkksss aalloott :) – cV2

1

esta es mi aplicación LocationListener para filtrar onLocationChanged() eventos innecesarios:

NOTA I usan mensajes en mi servicio.

public class GPSlocationListener implements LocationListener 
{ 
    //member variables 
    private Handler mParentHandler;//points to Handler of parent 
    private long mTimeBetweenLocationEvents; 
    private long mTimeOfLastLocationEvent; 
    private boolean mAccuracyOverride; 
    private float mLastAccuracy; 
    private boolean mOverrideLocation; 

    //constants 
    private static final float INVALID_ACCURACY = 999999.0f; 
    private static final String TAG = "GPSlocationListener"; 


    //constructor 
    public GPSlocationListener(Handler parentMsgHandler, long timeBetweenLocationEvents, boolean accuracyOverride) 
    { 
     mParentHandler = parentMsgHandler; 
     mTimeOfLastLocationEvent = 0; 
     mAccuracyOverride = accuracyOverride; 
     mLastAccuracy = INVALID_ACCURACY; 
     mOverrideLocation = false; 
     mTimeBetweenLocationEvents = timeBetweenLocationEvents; 
    } 

    //EVENT: onLocationChanged() 
    // send GPS coordinates to CommService 
    public void onLocationChanged(Location loc) 
    { 
     Log.d(TAG, "onLocationChanged() triggered. Accuracy = "+Float.toString(loc.getAccuracy())); 
     mOverrideLocation = false; 

     if (loc != null) 
     { 
      //if a more accurate coordinate is available within a set of events, then use it (if enabled by programmer) 
      if (mAccuracyOverride == true) 
      { 
       //whenever the expected time period is reached invalidate the last known accuracy 
       // so that we don't just receive better and better accuracy and eventually risk receiving 
       // only minimal locations 
       if (loc.getTime() - mTimeOfLastLocationEvent >= mTimeBetweenLocationEvents) 
       { 
        mLastAccuracy = INVALID_ACCURACY; 
       } 


       if (loc.hasAccuracy()) 
       { 
        final float fCurrentAccuracy = loc.getAccuracy(); 

        //the '<' is important here to filter out equal accuracies ! 
        if ((fCurrentAccuracy != 0.0f) && (fCurrentAccuracy < mLastAccuracy)) 
        { 
         mOverrideLocation = true; 
         mLastAccuracy = fCurrentAccuracy; 
        } 
       } 
      } 

      //ensure that we don't get a lot of events 
      // or if enabled, only get more accurate events within mTimeBetweenLocationEvents 
      if ( (loc.getTime() - mTimeOfLastLocationEvent >= mTimeBetweenLocationEvents) 
       ||(mOverrideLocation == true)) 
      { 
       //be sure to store the time of receiving this event ! 
       mTimeOfLastLocationEvent = loc.getTime(); 

       //send message to parent containing the location object 
       Message msgToMain = mParentHandler.obtainMessage(); 
       msgToMain.what = Constants.MSG_LOCATION_CHANGED; 
       msgToMain.obj = loc; 
       mParentHandler.sendMessage(msgToMain); 
      } 
     } 
    } 

    public void onProviderDisabled(String provider) 
    { 
     // TODO Auto-generated method stub 
    } 

    public void onProviderEnabled(String provider) 
    { 
     // TODO Auto-generated method stub 
    } 

    public void onStatusChanged(String provider, int status, Bundle extras) 
    { 
     // TODO Auto-generated method stub 
    } 

} 

esto se implementa de la siguiente manera en el código principal:

//create the APIthread (which exposes mAPIhandler back to this service) 
mAPIthread = new APIthread(mApiHandler); 
mAPIthread.start(); 


//use the LocationManager class to obtain GPS locations 
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  

locationListener = new GPSlocationListener(mApiHandler, Constants.LOCATION_UPDATE_PERIOD_MSEC, true); 

//this will call GPSlocationListener.onLocationChanged() 
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
             //3 mins NOTE: approximate value 
             Constants.LOCATION_UPDATE_PERIOD_MSEC, 
             //no distance updates desired 
              0, 
              locationListener); 
+0

con accuracyOverride enabled, esto reducirá los mensajes por evento onLocationChanged() a dos o tres cada período de tiempo. De lo contrario, solo uno. PD public static final int LOCATION_UPDATE_PERIOD_MSEC = 3 * 60 * 1000; // 3 mins –

7

me encontré con esta pregunta porque tenía el mismo problema.

Creo que tengo la respuesta. Las actualizaciones rápidas están siendo despedidos porque tiene el parámetro metros ajustado a 0.

Cambiar el parámetro metros a algo así como 10 y sólo se disparará el evento LocationChanged cada 2 minutos si su ubicación cambia por 10 o más.

Antes de realizar este cambio, LocationChanged estaba disparando varias veces por segundo. Ahora, dispara una vez. Luego, cada 2 minutos, verá el ícono de GPS en la barra de estado, pero a menos que cambie su ubicación, el evento no se activará.

Espero que esto ayude. Esto es lo que me solucionó.No tuvo que agregar ninguna lógica adicional para evitar incendios falsos.

+1

+1 - Mi configuración actual era de 10 metros, cada 60000 ms (1 minuto) y el monitor de ubicación estaba disparando cada 5-10 segundos mientras estaba estacionario. Cambié la distancia a 20 metros y las actualizaciones llegaron * mucho * con menos frecuencia ... pero aún esporádicas e impredecibles. –

+2

+1 - Esto funcionó para mí también. – NarendraJi

Cuestiones relacionadas