Search code examples
javaandroiddelay

Creating delay between measurements


I am trying to make a set of measurements of signal strength, so i want to make a delay between same method (that return needed value) execution - value1...delay....value2....delay.... Currently i am using

Thread.sleep(DELAY);

Such way of creating the delay seems to work, but as I understood it makes the whole app to stop. I have looked through Android Developers website and found some other ways using Timer and ScheduledExecutorService. But i do not fully understand how to create a delay using those 2 ways. May be someone will be some kind and give me some ideas or directions to start with?


Solution

  • You could use a Runnable and a handler.

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
    
            // Get the difference in ms
            long millis = SystemClock.uptimeMillis() - mStartTime;
    
            // Format to hours/minutes/seconds
            mTimeInSec = (int) (millis / 1000);
    
            // Do your thing
    
            // Update at the next second
            mHandler.postAtTime(this, mStartTime + ((mTimeInSec + 1) * 1000));
        }
    };
    

    And start this with a handler:

    mHandler.postDelayed(mUpdateTimeTask, 100);
    

    Ofcourse you have to have a global mHandler (private Handler mHandler = new Handler();) and a starting time (also the uptimeMillis). This updates every second, but you can change it for a longer period of time. http://developer.android.com/reference/android/os/Handler.html