Sunday, March 20, 2011

Sending a Single SMS to Multiple Addressees

The net-net-net of this, if you're wondering is, it can't be done.  Hear me out.  I don't want to send 10 SMS messages to 1 addressee.  I can do that just fine.  I was trying to send a single message to 10 addressees in order to get 1,000 addressees the same message rather than Android's 100 addressees/messages.  I learned a valuable lesson about the SDK documentation.  When it says it accepts a "String" it doesn't mean you can trick it to accept a String [].


public void sendDataMessage (String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent)

I spent a lot of time yesterday getting the code in place to provide "destinationAddress" as a comma (as well as space, semicolon, and new line) delimited list.  No messages get sent unless your list contains only 1 item.  *sigh*

But, I do like the code I came up with so I'm storing it here in the hopes that it might someday be useful in another context.


protected void sendMsg(Context context, SmsMessage smsMessage) {
        SmsManager smsMgr = SmsManager.getDefault();
        ArrayList<string> smsMessageText = smsMgr.divideMessage(smsMessage.getMsgBody());
        PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent("SMS_SENT"), 0);
        PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent("SMS_DELIVERED"), 0);
        int AddresseesPerMessage = 10;
        StringBuilder builder = new StringBuilder();
        String delim = "";
        for (ContactItem c:smsMessage.getAddresseeList()) {
            //  For every phone number in our list
            builder.append(delim).append(c.getPhoneNumber().toString());
            delim=";";
            if (((smsMessage.getAddresseeList().indexOf(c)+1) % AddresseesPerMessage) == 0 || smsMessage.getAddresseeList().indexOf(c)+1 == smsMessage.getAddresseeList().size()) {
                // using +1 because index 0 mod 9 == 0 
                for(String text : smsMessageText){
                    //  Send 160 bytes of the total message until all parts are sent
                    smsMgr.sendTextMessage(builder.toString(), null, text, sentPI, deliveredPI);
                }
                builder.setLength(0);
                delim="";
            }
        }
    }