17

What should I pass as second parameter<"format"> to createFromPdu() method,

SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i], format);

As in latest version of android following line of code is deprecated,

SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);

I have searched on Internet but nothing was clear to me. I have read into android doc too,

http://developer.android.com/reference/android/telephony/SmsMessage.html#createFromPdu(byte[], java.lang.String)

Kislay Kumar
  • 243
  • 1
  • 2
  • 10

1 Answers1

52

Basically this was introduced for Android Marshmallow to support "3gpp" for GSM/UMTS/LTE messages in 3GPP format or "3gpp2" for CDMA/LTE messages in 3GPP2 format.

Here is the full example for SMSReceiver:

public class SMSReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent)
{
    Bundle myBundle = intent.getExtras();
    SmsMessage [] messages = null;
    String strMessage = "";

    if (myBundle != null)
    {
        Object [] pdus = (Object[]) myBundle.get("pdus");

        messages = new SmsMessage[pdus.length];

        for (int i = 0; i < messages.length; i++)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                String format = myBundle.getString("format");
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
            }
            else {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            }
            strMessage += "SMS From: " + messages[i].getOriginatingAddress();
            strMessage += " : ";
            strMessage += messages[i].getMessageBody();
            strMessage += "\n";
        }

        Log.e("SMS", strMessage);
        Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
    }
}
}
Alexi Akl
  • 1,934
  • 1
  • 21
  • 20
  • I believe it would be better if you take the statement `String format = myBundle.getString("format");` outside of the loop just under `Object [] pdus = (Object[]) myBundle.get("pdus");` would be good – Tristus Oct 14 '16 at 00:09
  • In my case I could not read sms in Google nexus device with this code while I have implemented runtime permission for read sms, send sms, received sms and read contact. – Ranjeet Kushwaha May 16 '17 at 10:58
  • @Alexi Akl Hello. Can anyone explain to me if using this method we get one single message or more? What if I assign 0 to `String smsMessage = messages[0];` ? Is that the message? – JPerk May 17 '17 at 17:12