我正在使用“遗留代码”来阅读Android中的传入短信。代码如下:
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
String smsSender ="";
String smsBody = "";
long smsTimestamp = 0L;
Object[] pdu_list = (Object[]) bundle.get("pdus");
for (Object pdu : pdu_list) {
SmsMessage msg = SmsMessage.createFromPdu((byte[])pdu);
if (msg == null) continue;
smsSender = msg.getOriginatingAddress();
smsBody += msg.getMessageBody().toString();
smsTimestamp = msg.getTimestampMillis();
}
...
如果pdu_list有多个成员怎么办?当它包含两个或更多PDU时,它们是指相同的长/连接短信还是真正不同的短信?
在上面的代码中,我连接了文本消息体,但我不确定它是否正确。
答案 0 :(得分:0)
这是获取短信文本和号码的工作代码。
@Override
public void onReceive(Context context, Intent intent) {
ctx = context;
String str = "";
Log.i(TAG, "Intent recieved: " + intent.getAction());
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
System.out.println(" ---Recieved1 ");
if (bundle != null) {
System.out.println(" ---Recieved2 ");
Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
System.out.println("Message");
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += "SMS from "
+ messages[i].getOriginatingAddress().replaceAll(
"[^a-zA-Z0-9 ]", "");
str += " is ";
str += messages[i].getMessageBody().toString();
str += "";
}
}}}