2

I need tu update my TextView every second. I wrote it with Timer and TimeTask but everyone says its deprecated method. Can someone show me how to make simple timer which updates TextView every 1 second with possibility stop it from UI?

SpeedEX505
  • 1,976
  • 4
  • 22
  • 33

3 Answers3

9

You can use a handler or a count down timer

Handler m_handler;
Runnable m_handlerTask ;  
m_handler = new Handler();   
m_handlerTask = new Runnable()
{
  @Override 
  public void run() { 

    // do something. update text view.  
    m_handler.postDelayed(m_handlerTask, 1000);    

  }
  };
 m_handlerTask.run();

To stop

m_handler.removeCallbacks(m_handlerTask);

Check this link for countdowntimer ,handler, timer

Android Thread for a timer

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
7

No need to create a separate Handler for this (as in the currently accepted answer). In stead, just postDelayed() the Runnable directly to the TextView's internal message queue:

Runnable runnable = new Runnable () {
    @Override public void run() {
        // do some work, then repost:
        textview.postDelayed(runnable, 1000);
    }
};
// post with an initial 1000 ms delay
textview.postDelayed(runnable, 1000);
// or post without an initial delay
textview.post(runnable);
// or even run the runnable right away the first time
runnable.run();

Alternatively, if all you're trying to accomplish is to 'redraw' the TextView, use invalidate() (or postInvalidate() from a non-UI thread). There are also overloads that allow you to restrict the invalidation to a specific rectangle, which you can potentially exploit for a more efficient implementation.

MH.
  • 45,303
  • 10
  • 103
  • 116
0

You could use a simple handler to do what you need to do. Anyway, with the scheduler way you could do:

private ScheduledExecutorService scheduler;
...    

if(scheduler != null)
{
    scheduler.shutdown();
    scheduler = null;
}

scheduler = Executors.newSingleThreadScheduledExecutor();

scheduler.scheduleAtFixedRate(new Runnable()
{
    public void run()
    {
         // do your stuff...
    }
}, Consts.KEEP_ALIVE_TIMEOUT, Consts.KEEP_ALIVE_TIMEOUT, TimeUnit.MINUTES);
fasteque
  • 4,309
  • 8
  • 38
  • 50