I'm currently trying to code an app to send mass SMS to 300+ numbers I have in my database.
I'm facing issues with sending them all at one go my app will force close and I only managed to send like 27/308.
I'm using a for loop to send my SMSes.
Is this any fix for this where I can delay my for loop for like 1-2 seconds before going to the next step?
Currently I've tried this code but it only sleep for 20seconds then it'll do all the steps at one go instead of 20sec per step. Commented out my sendSms method and tested with println();
Any help would be greatly appreciated.
for (i = 0; i < phoneNumbers.length; i++){
txtCommand = customIDs[i] + ";" + command + ";&W<";
if (phoneNumbers[i].length()>0 && txtCommand.length()>0) {
final String Messages = "Phone Number:" + phoneNumbers[i] + " " + "Message:" + txtCommand;
myHandler.postDelayed(new Runnable() {
public void run() {
System.out.println(Messages);
//sendSMS(phoneNumbers[i], txtCommand);
}
}, 20000);
}
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
The code as written will queue everything to run 20 seconds after the for loop. But what you want is for each task to be queued to run 20 seconds after the previous one.
You could try multiplying your delay by the index:
myHandler.postDelayed(
...
, (i + 1) * 20000);
Or, you could rewrite your loop recursively:
void queueMessage(final String[] phoneNumber, final int index) {
if (index < phoneNumber.length) {
// TODO do your validation here
myHandler.postDelayed(new Runnable() {
public void run() {
// TODO do your work here
queueMessage(phoneNumber, index + 1);
}
}, 20000);
}
}
As an aside, if you're not already running this loop in a service, you should.