I am trying to implement a simple digital clock with second and two colons changing every second. I have thought about using DigitalClock but I want the colons to flash as well as the second and don’t want to show am/pm. So I read the “Updating the UI from a Timer” and it suggests us to use Handler. So i use Handler and can change second and colons every second but the weird thing is that sometimes, it jumps a second (1,2,4,5,6). It seems the clock is a bit lagging. Is there any way to solve this problem? Thanks!
tick_handler = new Handler();
Runnable updateSecond = new Runnable(){
@Override
public void run() {
second.setText(DataModel.getSeconds());
if(colon1.getVisibility()== View.VISIBLE){
colon1.setVisibility(View.INVISIBLE);
colon2.setVisibility(View.INVISIBLE);
} else {
colon1.setVisibility(View.VISIBLE);
colon2.setVisibility(View.VISIBLE);
}
tick_handler.postDelayed(this, 1000);
}
};
tick_handler.postDelayed(updateSecond, 0);
I suspect that you see this on the emulator as it is much slower than actual phones. Try changing the
tick_handler.postDelayed(this, 1000);to a smaller value than 1 second, for e.g. 500 msand add a global variable to track the differece between each time the thread runs and if the difference is 1 second, update the Views.