How to make a delay or cause a wait on Android?

Asked

Viewed 140 times

0

I have a for where it sweeps a vector String, sending command completed increment .

for(int i=0; i < msg.size(); i++)
{
     enviarComando(msg.get(i));
} 

When he sends I want him to wait 1 second for each shipment.

I tried to use and this code inside for, but I did not succeed, it does not wait 1 seconds expected.

final Handler handler = new Handler();

handler.postDelayed(new Runnable() {
    @Override
    public void run() {


   }
}, 1000);

1 answer

3

The problem, apparently, is that you are trying to make this delay within Uithread (or Main Thread if you prefer). By definition Uithread cannot contain any element that is blocking the user (which also include delay methods like Thread.Sleep()) so to solve your problem just launch a new thread and run its processing on this new thread:

new Thread(() -> {
    for(int i=0; i < msg.size(); i++) {
        try {
            Thread.sleep(1000);
         } catch (InterruptedException ex) {
            ex.printStackTrace();
         }

         enviarComando(msg.get(i));
    }
}).start();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.