Question

I'm trying to send multiple SMS messages. My code:

for (Entry<String, String> entry : book.entrySet()) {
    sendSMS(entry.getValue(), message);
}

sendSMS:

private void sendSMS(final String phoneNumber, String message) {
        String SENT = "SMS_SENT";
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
                SENT), 0);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    System.out.println("sent");
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    System.out.println("No network "+ phoneNumber);
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    break;
                }
            }
        }, new IntentFilter(SENT));
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
    }

But the cases are performed several times. For 4 contcts:

  1. No network 123456879
  2. No network 123456879
  3. No network +79206501013
  4. No network 123456879
  5. No network +79206501013
  6. No network +79206501012
  7. No network 123456879
  8. No network +79206501013
  9. No network +79206501012
  10. No network 987654321

What could be the reason? Thanks!

Was it helpful?

Solution

I think moving the registerReceiver(...) outside of sendSMS will solve this. This seems to be a case of multiple registrations.

Try something like this

Intent smsSentIntent = new Intent(SENT);
smsSentIntent.setClass(context, SmsSentBroadcastReceiver.class);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top