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?
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
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.
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);
Related
I want to delay the app before updating the messages to make it look realistic.
when I am trying to delay updating one message it works just fine as shown below
if (currentMessage.getMessageStatue() == MESSAGE_RECEIVED) {
handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
updateMessage();
notifyAdapter();
currentMessage++;
}
};
handler.postDelayed(runnable, 3000);
}
But the problem is that when I am trying to loop throw each message and perform the same task, the app keeps delaying and android force it to stop. this is what I am trying to do:
while (currentMessage.getMessageStatue() == MESSAGE_RECEIVED) {
handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
updateMessage();
notifyAdapter();
currentMessage++;
}
};
handler.postDelayed(runnable, 3000);
}
can I overcome this issue and use a postDelayed handler inside a while loop?
I have simple runnable like so
private Runnable runnable = new Runnable()
{
#Override
public void run()
{
someVariable = true;
}
};
I use it with a Handler and delay like this
handler.postDelayed(runnable, 60000);
if this functionality gets spammed and the above is called repeatedly it adds runnable multiple times to the message queue.
if this is the case is there away to check if there is one in the message queue first before adding another?
Hi the way I do is to remove the messages and callbacks after my handler runs once. A simple example of my code would be
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
Log.d("runnable", "handler invoked just once");
handler.removeCallbacksAndMessages(null);
}
};
handler.postDelayed(runnable, 2000);
handler.postDelayed(runnable, 2000); // demo: if this is called multiple times my runnable code wont run
I'm working on an android Tetris game. And an IllegalStateException occurred when executing
timer.scheduleAtFixedRate (task, 0L, milliseconds);
in
public void setTimerInterval (int milliseconds) {
timer.cancel ();
timer = new Timer ();
timer.scheduleAtFixedRate (task, 0L, milliseconds);
}
Am I doing this wrongly or something?
I need to cancel the timer and create a new one because I cannot change the interval of the timer unless you schedule a new task for it, right?
I read a post here and here is a quote of one of the answers:
A timer can only be scheduled once. If IllegalStateException isn't happening when you call cancel(), but when you try to reschedule the timer, just reinstantiate the timer and then schedule it. Otherwise, I'm not sure.
I didn't use the accepted answer of the that question because it's about pausing and resuming the timer.
I reinstantiated the timer as shown above but there is still a IllegalStateException.
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// do the task here
handler.postDelayed(this, milliseconds); // set time here to refresh textView
}
});
Make the milliseconds global and change that, maybe that would be a better solution.
How to change a java timer's interval
Java Timers don't have intervals. Timer tasks have intervals.
Solution: cancel and reschedule the TimerTask, not the Timer.
My Testprogram should change a TextViews text and after it is done, it should wait on second before the next text change. However my program runs the text changes instant behind each other:
t.setText("Test!");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
t.setText("Test - after 1 second!");
}
},1000);
The first text is not even there close to a second.
Hard to say why that wouldn't work from that limited amount of code but you can just add the post delayed to your View. You don't need a handler.
t.setText("Test!");
t.postDelayed(new Runnable() {
#Override
public void run() {
t.setText("Test - after 1 second!");
}
}, 1000);
All Views in Android have a built in handler class.
You are missing the following:
handler.postDelayed(this, 1000);
inside the run method. Here this will refer to the handler object
How can this be done in android?
public final Timer timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do task here
}
});
I need to be able to call timer.start(); from the Activity that timer is in.
In most cases it is much better to use a Handler instead of Timer. Handler is capable of sending delayed messages. Benefits of using Handler are:
it runs on the main (UI) thread -> can access Views (unlike the
Timer, which cannot dircetly access Views)
You can remove pending delayed messages if you want
Less code
Example:
class MyActivity extends Activity {
private static final int DISPLAY_DATA = 1;
// this handler will receive a delayed message
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// Do task here
if (msg.what == DISPLAY_DATA) displayData();
}
};
#Override
void onCreate(Bundle b) {
//this will post a message to the mHandler, which mHandler will get
//after 5 seconds
mHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 5000);
}
}
Android has a nice CountDownTimer class, too
Try something like this:
// this will run when timer elapses
TimerTask myTimerTask = new TimerTask() {
#Override
public void run() {
// ...
}
};
// new timer
Timer timer = new Timer();
// schedule timer
timer.schedule(myTimerTask, delayInMs);
If you want task to be done in activity's main thread, modify it like this:
// get a handler (call from main thread)
final Handler handler = new Handler();
// this will run when timer elapses
TimerTask myTimerTask = new TimerTask() {
#Override
public void run() {
// post a runnable to the handler
handler.post(new Runnable() {
#Override
public void run() {
// ...
}
});
}
};
// new timer
Timer timer = new Timer();
// schedule timer
timer.schedule(myTimerTask, delayInMs);
I have answered this in another question.
I would avoid the TimerTask, if you fire a lot of them off, they are not only difficult to manage but bad for performance.
I would recommend a Handler for pretty much any Time based task these days.
See Timer application