private IntentFilter receiceFilter;
private MessageReceiver messageReceiver;
private void init(){
receiceFilter=new IntentFilter();
receiceFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
messageReceiver=new MessageReceiver();
registerReceiver(messageReceiver,receiceFilter);
}
别忘了在Destroy的时候反注册
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(messageReceiver);
}
定义的短信的接收器
class MessageReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
Object[]pdus= (Object[]) bundle.get("pdus");//提取短信消息
SmsMessage[] messages=new SmsMessage[pdus.length];
for (int i=0;i<messages.length;i++){
messages[i]=SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String address=messages[0].getOriginatingAddress();//获取发送方的号码
String fullMessage="";
for (SmsMessage message:messages){
fullMessage+=message.getMessageBody();//获取短信内容
}
}
}
最后别忘了 加个读取信息的权限
<uses-permission android:name="android.permission.READ_SMS"/>