Search code examples
androidgpslocationlistener

What is the best way to get the location in android every 5 sec


what is the best way and bestpower-saving mode to get the following things in Android with LocationListener every 5 secounds:

  1. Location (Latitude, Longitude)
  2. Accuracy
  3. Altitude
  4. Speed
  5. Bearing
  6. ...

I tried this (LocationListener):

 @Override
public void onLocationChanged(Location location) {
   // ...Code...
}

But this only update if Location changed but I need every 5 sec and only there. Maybe someone can show me an example.

Thanks for answers.


Solution

  • Use rxJava's method Observable.interval(5, TimeUnit.Seconds). ... and ubsubscribe from it when updates are no longer needed. In event handling (subscribe()) method poll location manually.

    Subscription pollingConnection = Observable.interval(5, TimeUnit.SECONDS)
                    .observeOn(Schedulers.computation())
                    .map(t -> {
                        // get all your readings manually (it is executed in background because of
                        //  .observeOn(Schedulers.computation())
                        return  t;
                    })
                    .subscribe(t -> {
                    }, e -> {
                    });
    
            // call pollingConnection.unsubscribe(); when update is no longer needed