0

in my app I am writing data to a CSV file every second. I am using a Handler with postAtTime for this purpose. This works fine as long as the screen is on. The data gets written almost exactly every second. For example the data looks like this (seconds.milliseconds):

  • 24.288
  • 25.293
  • 26.293
  • 27.293
  • 28.298
  • 28.296

As you can see, the difference is always a second plus a few milliseconds which is perfectly fine.

However if you turn the screen off or you go back to the home screen (everytime onPause() is called) the handler is still running, but with a more significant delay:

  • 30.610
  • 31.651
  • 32.690
  • 33.715
  • 34.751
  • 35.791

This time the delay is around 40 ms. If I switch to the app again or turn the screen back on the delay is minimal again (one or two ms). Is there a way to avoid this delay when the app runs in the background or is this an android limitation? Is there a better/more precise possibility than using a handler?

This is the code in the onResume() method:

try {
        this.csvHandler.removeCallbacksAndMessages(null);
} catch (Exception e1) {
}
this.csvHandler = new Handler();
this.csvHandler.postDelayed(new Runnable() {

        @Override
        public void run() {
            long currentTime = SystemClock.uptimeMillis();
            if (currentTime > runAtTime) {
                calendar = GregorianCalendar.getInstance();
                runAtTime = currentTime + 1000;                 
                writeToCSV();
            }
            csvHandler.postAtTime(this, runAtTime);
        }
    }, 0);

runAtTime has been initialized with 0.

writeToCSV method:

String[] data = {this.simpleDateFormatCSV.format(this.calendar.getTime())};         
this.csvWriter.writeNext(data);

The csvWriter is of type com.opencsv.CSVWriter.CSVWriter.

onPause() and onStop() are empty.

Thanks!

Luigi04
  • 437
  • 5
  • 14

1 Answers1

0

The mistake actually was to get the currentTime on every run. Instead now I am only getting the currentTime once in onCreate() and then just adding the 1000ms period to runAtTime.

in onCreate()

this.runAtTimeRefresh = SystemClock.uptimeMillis();

run()

runAtTime += 1000;
writeToCSV();
csvHandler.postAtTime(this, runAtTime);
Luigi04
  • 437
  • 5
  • 14