1、权限和创建广播

<!-- 设置权限 -->
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

 

<!-- 创建receive聆听系统广播信息 -->
<receiver android:name=".MyReceiver">
<!-- 设置要捕捉的信息名称为provider中Telephony.SMS_RECEIVED -->
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>

2、代码

public class MyReceiver extends BroadcastReceiver{
@SuppressWarnings("deprecation")
public void onReceive(Context context,Intent intent){
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
StringBuilder sb=new StringBuilder();
Bundle bundle=intent.getExtras();
if(bundle!=null){
Object[] obj=(Object[])bundle.get("pdus");//获取短信信息
SmsMessage[] sm=new SmsMessage[obj.length];
int length=obj.length;
for(int i=0;i<length;i++){
sm[i]=SmsMessage.createFromPdu((byte[])obj[i]);//获取短信信息
}
for(int i=0;i<length;i++){
sb.append("来自: \n");
sb.append(sm[i].getDisplayOriginatingAddress());//电话号码
sb.append("的短信;");
sb.append("信息为: \n");
sb.append(sm[i].getMessageBody());//短信内容
}
Toast.makeText(context, sb.toString().trim(), Toast.LENGTH_SHORT).show();
Intent tempIntent=new Intent(context,MainActivity.class);
tempIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(tempIntent);
}
}
}

}