I'm using "legacy code" to read incoming SMS in Android. The code is the following:
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();
}
...
What if pdu_list has more than one member? When it contains two or more PDUs, do they refer to the same long/concatenated SMS or to really different messages?
In the above code, I concatenate the text message body, but I'm not sure it is the right thing to do.
this is working code to get sms text and number.
@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 += "";
}
}}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.