Delay for loop cycle in Java

2019-09-13 03:35发布

问题:

I am building an SMS messaging app, with a list of phone numbers in an array which I would like to send to. When I press the SEND button in the app, the message that I type would be sent to all the numbers in that array.

I am using a for loop to run through the numbers and sending the same message to each of them:

for (i=0; i<names.length; i++) {
    phoneNo = names[i][3];
    sendMessage(phoneNo, message);
}

private void sendMessage(String phoneNo, String message) {
    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, message, null, null);
        Toast.makeText(getApplicationContext(), "SMS sent", Toast.LENGTH_LONG).show();
    }
    catch (Exception e) {
        Toast.makeText(getApplicationContext(), "SMS failed. Please try again!", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

This works perfectly, but now, I want to introduce a one-second delay between sending each message, so I've modified my for loop as follows:

Handler handler1 = new Handler();
for (i=0; i<names.length; i++) {
    handler1.postDelayed(new Runnable() {
        @Override
        public void run() {
            phoneNo = names[i][3];
            sendMessage(phoneNo, message);
        }
    }, 1000);
}

This is syntactically correct, but my app crashes whenever I try to send a message now. Can somebody please point out what I've done wrong?

Many thanks:-)