In an app I'm working on I need to have a timer that tracks the time from the first login until a certain goal is met. For the timer I have been using a Chronometer.
My problem is that the timer will reset if the user force-closes the app from their background apps. I need the timer to persist and update even if the app is force-closed by the user.
Currently, my code looks as follows:
try{
FileInputStream fileIn = openFileInput(timerFilename);
InputStreamReader InputRead = new InputStreamReader(fileIn);
char[] timeInputBuffer = new char[HomeScreen.READ_BLOCK_SIZE];
t="";
int timeCharRead;
while((timeCharRead = InputRead.read(timeInputBuffer))> 0){
String readString = String.copyValueOf(timeInputBuffer, 0, timeCharRead);
t += readString;
}
InputRead.close();
} catch(Exception e){
e.printStackTrace();
}
if(t == null) {
try {
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
FileOutputStream fileout = openFileOutput(timerFilename, MODE_PRIVATE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
outputWriter.write(Long.toString(SystemClock.elapsedRealtime()));
outputWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
else{
long currentTime = SystemClock.elapsedRealtime() - Long.parseLong(t);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
mChronometer.setBase(currentTime);
mChronometer.setText(sdf.format(new Date(currentTime)));
mChronometer.start();
}
I have omitted some unrelated code for brevity.
The main issue is that after supplying the currentTime
long to mChronometer.setBase()
and then calling mChronometer.start()
the timer seems to be completely random and not start where I want it to.
I understand from researching online that calling setBase() and start() will still cause the timer to start counting from 00:00 but I was under the impression that calling mChronometer.setText()
should solve that problem, which it is not.
So my question, how can I keep the timer on-time even if the app is forcibly closed?