I’m searching for the easiest solution to implement a self updating digital clock in Android. I know that there is already digital clock class: http://developer.android.com/reference/android/widget/DigitalClock.html
and yes it’s also deprecated. From API 17 we now use TextClock. Anyways for the sake of learning i want to make my own custom clock showing hh:mm:ss and of course should updating itself.
So far i make reference to my textview ( where digital clock will be displayed ), and i got instance of Calendar class and i also sign minutes, hours and seconds to instance variables:
Calendar cal = Calendar.getInstance();
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
sec = cal.get(Calendar.SECOND);
clock.setText(hour+":"+min+":"+sec);
If i run this code, the accurate time is displayed on emulator but obviously it’s not updating. What i must do, so my code will “looping” and updating my clock?
I already checked this nice answer: Android: How do I display an updating clock in a TextView but my question is: I want the easiest solution of digital clock in android =) Do i still need to use Handler?
Well using a Handler isn’t that difficult. One possible implementation is (note: I didn’t check if it leaks or not):
If you don’t want to use Handler, you could also use a CountDownTimer with
millisInFutureset toLong.MAX_VALUE. But this is really a hack and I don’t know if Android implementation can handle the integer overflow correctly.