The effects of firing off a runnable multiple times using a Handler - java

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

Related

postDelayed inside while loop doesn't work?

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?

Java SWT UI Thread freeze even if run in new Thread

I have a problem with a long running task.
After my dialog is shown I want to scan a ftp directory. This task takes some time so I need to run this task no in the UI thread.
My idea was
#Override
protected void postDialogOpen() {
// if invoked via menu button
if (!scanFtp) {
final Display display = Display.getDefault();
new Thread(new Runnable() {
#Override
public void run() {
//initProgressWaitViewer();
scanFtpServer();
//closeProgressWaitViewer();
display.syncExec(new Runnable() {
#Override
public void run() {
updateTree();
}
});
}
}).run();
}
}
But during the execution of scanFtpServer() my dialog is not movable and if I click on it it becomes "unresponsible".
Is there something I am doing wrong?
When calling method run() in class Thread, you are executing the method on the caller thread, just like calling any other method. If you want to spawn a new thread and execute method run() in that thread, you need to call method start() instead, that will do all the work of setting up the thread and running it.
So replace
}).run();
with
}).start();
Try to do .start() instead of .run() .

update TextView every second with ScheduledThreadPoolExecutor

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);

Using handler/runnable to delay the resubmission of a method

I want to run the getVehicles() method every 10 seconds, I have the following code:
Handler vehiclehandler = new Handler();
final Runnable vehiclerunnable = new Runnable() {
public void run() {
getVehicles(null);
vehiclehandler.postDelayed(this, 10000);
}
};
Yet at the moment it does nothing, I've searched around and can't figure it out.
I'm new to android and have never used a handler before, only a runnable to tell something to 'runOnUiThread'.
did you run
vehiclehandler.post(vehiclerunnable)
at least once?
I mean outside the Runnable
final Handler lHandler = new Handler();
Runnable lRunnable = new Runnable() {
#Override
public void run() {
// do stuff
lHandler.postDelayed(this, 10000);
}
};
lHandler.post(lRunnable);
Here is an adjustment to your code that will make it run properly
Handler vehiclehandler = new Handler();
vehiclehandler.postDelayed(new Runnable(){
public void run(){
getVehicles(null);
}
},10000);
But this will just delay your code before get executed. If you want to repeat the process over and over again you have to use Timer, something like:
private static Timer timer = new Timer();
timer.scheduleAtFixedRate(new mainTask(), 0, 10000);
private class mainTask extends TimerTask
{
public void run()
{
getVehicles(null);
}
}

Java Timer in android

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

Categories