为什么`SmsMessage.createFromPdu`返回一个数组?

时间:2014-06-12 01:11:38

标签: android sms pdu

在Android中,如果我想阅读传入的短信,我会使用SmsMessage.createFromPdu,但这会返回SmsMessage的数组。这是为什么?为什么不只是一个SmsMessage?是因为长消息可以分为几个?如果是这样,这是否意味着我可以指望所有这些SmsMessage具有相同的起始地址?

2 个答案:

答案 0 :(得分:3)

经过大量的研究,这是交易:

是的,您获得的这些消息是较大消息的细分。

SmsMessage的数组包含可能相互关联或不相关的消息(不同的发件人)。 Android为何会将它们混合起来?我不知道。您应该始终循环遍历它们并按SmsMessage.getDisplayOriginatingAddress()对它们进行分组。然后,对于每组消息,从SmsMessage.getDisplayMessageBody()追加他们的主体以重建更大的消息。

以下是GTalk应用程序源代码的示例(感谢@hungryghost):

private static Map<String, String> RetrieveMessages(Intent intent) {
    Map<String, String> msg = null; 
    SmsMessage[] msgs;
    Bundle bundle = intent.getExtras();

    if (bundle != null && bundle.containsKey("pdus")) {
        Object[] pdus = (Object[]) bundle.get("pdus");

        if (pdus != null) {
            int nbrOfpdus = pdus.length;
            msg = new HashMap<String, String>(nbrOfpdus);
            msgs = new SmsMessage[nbrOfpdus];

            // There can be multiple SMS from multiple senders, there can be a maximum of nbrOfpdus different senders
            // However, send long SMS of same sender in one message
            for (int i = 0; i < nbrOfpdus; i++) {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);

                String originatinAddress = msgs[i].getDisplayOriginatingAddress();

                // Check if index with number exists                    
                if (!msg.containsKey(originatinAddress)) { 
                    // Index with number doesn't exist                                               
                    // Save string into associative array with sender number as index
                    msg.put(msgs[i].getOriginatingAddress(), msgs[i].getDisplayMessageBody()); 

                } else {    
                    // Number has been there, add content but consider that
                    // msg.get(originatinAddress) already contains sms:sndrNbr:previousparts of SMS, 
                    // so just add the part of the current PDU
                    String previousparts = msg.get(originatinAddress);
                    String msgString = previousparts + msgs[i].getMessageBody();
                    msg.put(originatinAddress, msgString);
                }
            }
        }
    }

    return msg;
}

答案 1 :(得分:1)

它返回一个数组,以支持连接的多部分SMS(对于长于正常~160字符限制的消息)。每条消息可能有也可能没有相同的始发地址,具体取决于它们是否共享相同的标题信息。

http://en.wikipedia.org/wiki/Concatenated_SMS

http://en.wikipedia.org/wiki/Protocol_data_unit

消息可能不按顺序发生,可能来自不同的发件人。请查看这些链接,以了解如何连接多部分SMS,包括一个好的代码示例。

Discussion on how to handle multi-part SMS

gtalksms code for concatenating pdus

相关问题