How do I delay or cause a wait on Android?

0

I have a for where it scans a String vector, sending command increment 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 this code inside for , but I did not succeed, it does not wait for 1 second expected.

final Handler handler = new Handler();

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


   }
}, 1000);
    
asked by anonymous 25.08.2018 / 18:57

1 answer

2

The problem, apparently, is that you are trying to make this delay inside the UIThread (or Main Thread if you prefer). By default the UIThread can not contain any element that is blocking the user (which also includes delay methods such as Thread.sleep ()) so to solve your problem, just launch a new thread and execute 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();
    
25.08.2018 / 21:58