我在查看来自原始短信的接收方电话号码时遇到问题。这是我正在尝试的代码:
有人能告诉我如何从原始短信中检索收件人的电话号码。
public class SMSReceiver extends BroadcastReceiver {
private Context context;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
// Parse the SMS.
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
// Retrieve the SMS.
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
//appending to str String.
str += "OriginatingAddress: ";
str += msgs[i].getOriginatingAddress();
str += " :\n";
str += " :\n";
str += "DisplayOriginatingAddress: ";
str += msgs[i].getDisplayOriginatingAddress();
str += " :\n";
str += " :\n";
str += "DisplayMessageBody: ";
str += msgs[i].getDisplayMessageBody();
str += " :\n";
str += " :\n";
str += "MessageBody: ";
str += msgs[i].getMessageBody();
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
提前感谢您的帮助!
答案 0 :(得分:3)
TelephonyManager不是正确的解决方案,因为在某些情况下,该号码未存储在SIM卡中,由于我的建议,您应该在应用程序打开时首次使用共享首选项来存储用户的电话号码,之后是号码将在您申请时随时使用。
如果您想获取发件人编号, 你只需要在广告的onReceive中调用这个方法,你就可以获得消息内容
messsage[0].getOriginatingAddress();
答案 1 :(得分:3)
SMS由MAP提供,MAP是SIM与MSC / GMSC / SMSC之间的协议(一些细节here)。 SIM已在此协会中标识。 SMS DELIVER也不包括收件人地址。见this。因此,据我所知,由于上述原因,可能没有您想要的直接API。
答案 2 :(得分:1)
使用内容提供商
Uri uri = Uri.parse("content://sms");
Cursor messageCursor = cr.query(uri, new String[] { "_id", "thread_id", "address", "date", "type", "body"}, null , null, "date" + " ASC");
messageCursor.moveToFirst();
String address = messageCursor.getString(messageCursor.getColumnIndex("address"));
String type = messageCursor.getString(messageCursor.getColumnIndex("type"));
....
答案 3 :(得分:0)
试试这个:
TelephonyManager manager =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = manager.getLine1Number();
这仅适用于存储在SIM卡上的号码的设备
答案 4 :(得分:-1)
public class SmsReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
// here you retrieve receiver phonenumber from msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}