Delay for loop cycle in Java

不打扰是莪最后的温柔 提交于 2020-01-06 20:21:39

问题


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

来源:https://stackoverflow.com/questions/38521653/delay-for-loop-cycle-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!