Search code examples
androidlocationgoogle-maps-android-api-2locationlistener

Run only once a code in locationlistener


I would like to run a code (get route to nearest location) only once, when location is fixed by the LocationListener, but each time the location gets an update the code runs. If i stop the location listener once the location is fixed my location will not get updates. Is it possible to run a code only once inside a locationlistener? How can i resolve this?


Solution

  • Please put a boolean in the location listener. If it runs first time, make the boolean as false, so next time the same code will not run in the location of the listener.

    boolean isFirstTime = true;
    

    At the location listener, use the following:

    if(isFirstTime){
       // Do your task which you want to do
    
       // and change flag to false.
       isFirstTime = false;
    }
    

    I hope this will help you.