1、新建一个广播接收器
public class SMSBroadcastReceiver extends BroadcastReceiver {private static final String TAG = "SMSBroadcastReceiver";private OnReceiveSMSListener mOnReceiveSMSListener;public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {Object[] pdus = (Object[]) intent.getExtras().get("pdus");for (Object pdu : pdus) {SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);// 短信号码String sender = smsMessage.getDisplayOriginatingAddress();Log.d(TAG, sender + "");//短信内容String content = smsMessage.getDisplayMessageBody();// 根据短信内容筛选if (content.contains("lgh") && content.contains("log")){if (mOnReceiveSMSListener!=null){Pattern pattern = Pattern.compile("\\d+");Matcher matcher = pattern.matcher(content);if (matcher.find()) {mOnReceiveSMSListener.onReceived(matcher.group());}abortBroadcast();}}/* // 根据号码筛选if ("136******".equals(sender) && mOnReceiveSMSListener != null) {Pattern pattern = Pattern.compile("\\d+");Matcher matcher = pattern.matcher(content);if (matcher.find()) {mOnReceiveSMSListener.onReceived(matcher.group());}abortBroadcast();}*/}}}/*** 回调接口*/public interface OnReceiveSMSListener {void onReceived(String message);}public void setOnReceiveSMSListener(OnReceiveSMSListener onReceiveSMSListener) {mOnReceiveSMSListener = onReceiveSMSListener;}}
2、在activity中动态设置调用
private SMSBroadcastReceiver mSMSBroadcastReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_loading_page);mSMSBroadcastReceiver=new SMSBroadcastReceiver();mSMSBroadcastReceiver.setOnReceiveSMSListener(this);// 注册广播IntentFilter intentFilter = new IntentFilter(SMSBroadcastReceiver.SMS_RECEIVED_ACTION);// 设置优先级intentFilter.setPriority(Integer.MAX_VALUE);registerReceiver(mSMSBroadcastReceiver,intentFilter);}@Overridepublic void onReceived(String message) {edit_code.setText(message);}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(mSMSBroadcastReceiver);}