BroadcastReceiver for multipart SMS

2019-01-28 03:19发布

I need to store sms to a sqlite db when I receive one. At this moment it works fine with sms (160 chars), but if I receive a multipart sms it truncate the sms at about 155 chars.

This is my code:

SmsBR.java

public class SmsBR extends BroadcastReceiver {
    private DBManager dbm;
        @Override
        public void onReceive(Context context, Intent intent) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        Object[] pdus = (Object[])bundle.get("pdus");
                        final SmsMessage[] messages = new SmsMessage[pdus.length];
                        for (int i = 0; i < pdus.length; i++) {
                            messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        }
                        if (messages.length > 0) {
                            dbm=DBManager.getDBM(null);
                            dbm.insertSMS(messages[0]);
                                                   }}}}

DBManager is a singleton class that I wrote to simplify read/write operations and I'm sure that it has no problem with long texts!

2条回答
劳资没心,怎么记你
2楼-- · 2019-01-28 03:43

according to several applications, it seems that multipart SMS are received in the same intent, and that they are represented by the messages array.

so basically, you retrieve the complete message:

StringBuffer content = new StringBuffer();
for (Message sms : messages) {
    content.append(sms.getDisplayMessageBody());
}
String mySmsText = content.toString();

As far as I know, it seems that the messages are in the correct order. Anyway, I don't know of any way to retrieve the message header (except parsing the pdu yourself).

查看更多
贼婆χ
3楼-- · 2019-01-28 03:47

155 chars sounds like the length of the user data when the user data header for a multipart SMS has been taken into account. In other words, it doesn't sound like there is a problem here - the PDU is being stored correctly. You will need to gather the other PDUs for the SMS to display / store the full thing.

查看更多
登录 后发表回答