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?
Asked
Active
Viewed 3,119 times
2
-
1why not use a handler – Raghunandan Aug 29 '13 at 08:49
-
use handler to update the text view in every second. – Yugesh Aug 29 '13 at 08:51
3 Answers
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

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
-
wow..awesome and so simple !works for me !! Thanks - I dont need any thread or timer. – Sree Reddy Menon Dec 19 '14 at 15:12
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