Search code examples
androidtextsmsbroadcastreceiverandroid-pendingintent

Android detect contents of failed message


So I am currently working on an application that involves sending text messages using a standard instance of SMSManager. Though there seems to be a relatively high fail rate when many messages are being sent consecutively. Is it possible to detect the contents of the failed text message (including the message body, and the recipient). This is how I currently detect if the message fails. BTW the sis object is a callback for another class to react to an unsent message.

    PendingIntent intent;
 intent = PendingIntent.getBroadcast(context, 0,
            new Intent("SMS_SENT"), 0);


registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent",
                            Toast.LENGTH_SHORT).show();
//send callback that a text message was successful
                    sis.messageSent();
                    break;
                default:
                    Toast.makeText(getApplicationContext(), "Message unsent", Toast.LENGTH_SHORT);
                    Bundle unsent = arg1.getExtras();
//send a call back that the message was unsent
//im trying to get the contents of the unsent message and pass it to another activity via a bundle but the pending intent is not returning any values(I checked it with a debugger)                    
sis.messageFailed();
                    break;
            }
        }
    }, new IntentFilter("SMS_SENT"));

Solution

  • The message is passed in intent extras you can get it this way:

    Bundle bundle=intent.getExtras();
    
    Object[] messages=(Object[])bundle.get("pdus");
    SmsMessage[] sms=new SmsMessage[messages.length];
    
    for(int n=0;n<messages.length;n++){
        sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
    }
    

    If SMS is short you can get message text with:

    String messageText = sms[0].getMessageBody();  
    

    If is long you should iterate sms array