我有一个广播接收器SMSApp,onReceive从intent读取bundleExtras。在这里,我如何从bundleExtras中读取电话号码?
if(intent.getAction().equals(SMS_RECEIVED))
{
Bundle bundleExtras = intent.getExtras();
if (bundleExtras != null)
{
}
}
答案 0 :(得分:11)
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]);
}
现在,messages[0].getOriginatingAddress()
是地址,messages[0].getMessageBody()
是邮件正文。
答案 1 :(得分:5)
http://ukitech.blogspot.com/2014/11/android-sms-app.html
教程输出:
SmsReceiver.processReceivedSms:来自+ 1650815xxxx的短信
SmsReceiver.processReceivedSms:SMS正文测试4
/ ** *由uki于11/22/14创建。 * /
公共类SmsReceiver扩展了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
答案 2 :(得分:0)
这是一个详细的“如何发送和接收短信”的链接,您应该检查它,它是完整的和完整的例子:
http://mobiforge.com/developing/story/sms-messaging-android
也可以使用此link,您可以这样做:
if (bundle != null) {
SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for (int i = 0; i < messages.length; i++) {
SmsMessage message = messages[i];
buf.append("Received SMS from ");
buf.append(message.getDisplayOriginatingAddress());
buf.append(" - ");
buf.append(message.getDisplayMessageBody());
}
}