Search code examples
androidmultithreadinggeolocation

android thread on repeated call method


I have a thread called checkUpdate inside this method:

public void onLocationChanged(Location location)
    checkUpdate = new Thread() {
        public void run() {
          try {
               // do some long staff using location variable            
              } catch (Exception e) {}
          handler.sendEmptyMessage(0);
        }
     };
    checkUpdate.start();

The problem is that the onLocationChanged() method is called by the system, sometimes before the thread has finished and this causes unpredictable behaviour in my application.

Is there any way to not run the thread if is already running or something similar?


SOLUTION:

I know what's going on, you need to call locationManager.removeUpdates(locationListener); and set locationManager=null on your destroy activity, otherwise even if the app is closed, the service is still running and fetching locations.


Solution

  • is there any way not to run the thread if is already running or something similar

    You could use an AtomicBoolean to set a value which tells you whether or not to start the thread. Then at the end of the run() method, you could reset the flag to be false.

    Something like the following should work:

    private final AtomicBoolean threadStarted = new AtomicBoolean(false);
    ...
    public void onLocationChanged(Location location) {
        if (threadStarted.compareAndSet(false, true)) {
            // start the thread
            checkUpdate = new Thread() {
                public void run() {
                    try {
                        // do thread stuff here
                    } finally {
                        // when the thread finishes, set the started flag to false
                        threadStarted.set(false);
                    }
                }
            };
            checkUpdate.start();
        }
    }