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!