我想从收到的短信中获取信息。像文本发件人身份的电话号码等信息。我正在尝试使用下面的代码。我有Manifest的权限。
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();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "n";
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
有效。但不是在Marshmallow 6.0.1 API上:23。此外,不推荐使用SmsMessage,createFromPdu和getMessageBody。我在Marshmallow找不到办法。请给我解决方案。
答案 0 :(得分:1)
BroadcastReceiver smsReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT < 19) {
if(Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())){
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs;
String sender;
if (bundle != null){
//---retrieve the SMS message received---
try{
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]);
sender = msgs[i].getOriginatingAddress();
String messageBody = msgs[i].getMessageBody();
// do things here
}
}
}catch(Exception e){
Log.d("Exception caught",e.getMessage());
}
}
}
}
else{
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
String messageBody = smsMessage.getMessageBody();
String sender = smsMessage.getOriginatingAddress();
// do things here
}
}
}
}
};
不要忘记注册接收者。 OnCreate中:
IntentFilter intentFilter = new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
intentFilter.setPriority(990);
registerReceiver(smsReceiver, intentFilter);
并取消注册。
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
threadTimer.interrupt();
}