Restart the requestLocationUpdates () with Sleep

2

How do I start requestLocationUpdates() with Thread.sleep(); on Android ?

My code:

public void onLocationChanged(Location loc) {
    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

    SQLiteDatabase db = openOrCreateDatabase("pontos.db", Context.MODE_PRIVATE, null);       
    db.execSQL("INSERT INTO pontos(latitude, longitude, datahora) VALUES('"+ loc.getLatitude()+"','"+loc.getLongitude()+"','"+  sdf.format(d)+"')");

   db.close();
 Toast.makeText(getBaseContext(), "Atualizado", Toast.LENGTH_LONG).show();      
 locationManager.removeUpdates(this);   
  incremento();



}

private void incremento() {
     new Thread(new Runnable() {

           @Override
          public void run() {

               try {

                  Thread.sleep(5000);
                                      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new Servico());

               }catch(Exception e){}

                 }
            }).start(); 


}

I call incremento(); at the end of onLocationChanged() , but nothing happens. Detail: This is a service in Background.

    
asked by anonymous 21.04.2014 / 13:55

1 answer

1

How LocationManager and LocationListener Work

The LocationListener.onLocationChanged() method is called whenever there is a new position obtained by GPS or antenna triangulation available (depending on whether you passed LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER to locationManager.requestLocationUpdates() ).

The execution of onLocationChanged() does not depend on how many times it is called locationManager.requestLocationUpdates() ; the latter only needs to be called once, and from there the onLocationChanged() method will be called repeatedly whenever a new position is available.

The onLocationChanged() method will always run on the main thread, and if memory does not crash, the locationManager.requestLocationUpdates() method must also be called from the main thread.

Pass this to it instead of new Servico() , and do not expect it to produce positions each time it is called, that is, do not match it with Thread.sleep() because that is not how it works. Receiving positions will stop when you call locationManager.removeUpdates(this) .

Suggested use

Start your position capture service by calling locationManager.requestLocationUpdates() and as soon as it is called onLocationChanged() , then call locationManager.removeUpdates(this) to stop fetching positions. Save the position obtained in the database and schedule the next execution of the service for some time in the future via the class AlarmManager .

In this way the service will run once for each position capture. If you know beforehand how long you want to call the service, do this schedule via AlarmManager with setRepeating() method.

    
21.04.2014 / 21:12