Sunday, February 3, 2013

Android Chronometer

Ha... (With great dissatisfaction...) I can't help but wonder what went through the mind of those who wrote that Chronometer component...

If you have tried to use this component, and have passed the System.currentTimeMillies() value to it, you are in for a surprise, Android's Chronometer is using the elapsed time, from SystemClock.elapsedRealtime().

Now I know I'm a big criticizer, but let me explain... I do understand the issues explained here, but really, who changes the System clock in their application? I've never encountered the need nor a requirement to perform such a system value abuse, and if you need to, double check your architecture!!

I find the component to be unnecessary, I would use a text view, update the time every 750ms, do it in 5 min, and would be still able to sleep at night, but there are people whom want to use this component... so be it.

Keep in mind that you still need to know that the base time needs to be an elapsedRealtime valid value, if you set the currentTimeMillis value you would/might see non-numeric characters in the Chronometer.

To solve this, your application should have something like this:

public class MyApplication
  extends Application {
 
 public static final long CurrentElapsedDelta = SystemClock.elapsedRealtime() - System.currentTimeMillis();
 
 public void setChronometer() {
  // When you want to set the chronometer base time you can use the following from anywhere in your code:
  long calculatedElapsedTime = System.currentTimeMillis() + MyApplication.CurrentElapsedDelta;
 
}

I've sketched this out of my head so it might a bit of fixing, I'll update this with a more reliable snippet.