4

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

4

2 回答 2

3

在进行了大量研究之后,交易如下:

是的,您收到的这些信息是更大信息的碎片。

s数组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;
}
于 2014-06-16T23:04:15.550 回答
1

它返回一个数组以支持串联的多部分 SMS(对于超过正常 ~160 字符限制的消息)。每条消息可能具有或不具有相同的原始地址,具体取决于它们是否共享相同的标头信息。

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

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

消息可能乱序并且可能来自不同的发件人。查看这些链接以讨论如何连接多部分 SMS,包括一个很好的代码示例。

关于如何处理多部分短信的讨论

用于连接 pdus 的 gtalksms 代码

于 2014-06-12T01:46:00.373 回答