I have a broadcast receiver SMSApp which onReceive reads bundleExtras from intent. Here, How can I read phone number from bundleExtras?
if(intent.getAction().equals(SMS_RECEIVED))
{
Bundle bundleExtras = intent.getExtras();
if (bundleExtras != null)
{
}
}
Bundle bundle = intent.getExtras();
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]);
}
Now, messages[0].getOriginatingAddress()
is the address and messages[0].getMessageBody()
is the message body.
Tutorial at http://ukitech.blogspot.com/2014/11/android-sms-app.html
OUTPUT:
SmsReceiver.processReceivedSms﹕ SMS from +1650815xxxx
SmsReceiver.processReceivedSms﹕ SMS body Test 4
/** * Created by uki on 11/22/14. */
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final String tag = TAG + ".onReceive";
Bundle bundle = intent.getExtras();
if (bundle == null) {
Log.w(tag, "BroadcastReceiver failed, no intent data to process.");
return;
}
if (intent.getAction().equals(SMS_RECEIVED)) {
Log.d(tag, "SMS_RECEIVED");
String smsOriginatingAddress, smsDisplayMessage;
// You have to CHOOSE which code snippet to use NEW (KitKat+), or legacy
// Please comment out the for{} you don't want to use.
// API level 19 (KitKat 4.4) getMessagesFromIntent
for (SmsMessage message : Telephony.Sms.Intents.
getMessagesFromIntent(intent)) {
Log.d(tag, "KitKat or newer");
if (message == null) {
Log.e(tag, "SMS message is null -- ABORT");
break;
}
smsOriginatingAddress = message.getDisplayOriginatingAddress();
//see getMessageBody();
smsDisplayMessage = message.getDisplayMessageBody();
processReceivedSms(smsOriginatingAddress, smsDisplayMessage);
}
// Processing SMS messages the OLD way, before KitKat,
// this WILL work on KitKat or newer Android
// PDU is a “protocol data unit”, which is the industry
// format for an SMS message
Object[] data = (Object[]) bundle.get("pdus");
for (Object pdu : data) {
Log.d(tag, "legacy SMS implementation (before KitKat)");
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
if (message == null) {
Log.e(tag, "SMS message is null -- ABORT");
break;
}
smsOriginatingAddress = message.getDisplayOriginatingAddress();
// see getMessageBody();
smsDisplayMessage = message.getDisplayMessageBody();
processReceivedSms(smsOriginatingAddress, smsDisplayMessage);
}
} // onReceive method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With