Running code again and again

In my application, I show the clock in a TextView , and I want to update it in real time. I tried to run it as follows:

 public void clock() { while(clock_on == true) { executeClock(); } } public void executeClock() { TextView timeTv = (TextView) findViewById(R.id.time); long currentTime=System.currentTimeMillis(); Calendar cal=Calendar.getInstance(); cal.setTimeInMillis(currentTime); String showTime=String.format("%1$tI:%1$tM %1$Tp",cal); timeTv.setText(showTime); } 

But that will not work.

0
source share
2 answers

Please, try:

 private Handler handler = new Handler(); runnable.run(); private Runnable runnable = new Runnable() { public void run() { // // Do the stuff // if(clock_on == true) { executeClock(); } handler.postDelayed(this, 1000); } }; 
+4
source

Use handler:

 private Handler handler = new Handler() { @Override public void handleMessage(android.os.Message msg) { TextView timeTv = (TextView) findViewById(R.id.time); long currentTime=System.currentTimeMillis(); Calendar cal=Calendar.getInstance(); cal.setTimeInMillis(currentTime); String showTime=String.format("%1$tI:%1$tM %1$Tp",cal); timeTv.setText(showTime); handler.sendEmptyMessageDelayed(0, 1000); } }; 
+3
source

Source: https://habr.com/ru/post/921952/


All Articles