今天博主带给小伙伴们一个小功能,就是利用广播接收器实现自动填充短信验证码,话不多说,我们先看看如何去实现这个小功能。
首先我们需要新建一个名为SMSBroadcastReceiver的广播接收器,代码如下:
public class SMSBroadcastReceiver extends BroadcastReceiver { private static MessageListener mMessageListener; public SMSBroadcastReceiver() { super(); } @Override public void onReceive(Context context, Intent intent) { public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; 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(); //短信内容 String content = smsMessage.getDisplayMessageBody(); long date = smsMessage.getTimestampMillis(); Date tiemDate = new Date(date); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = simpleDateFormat.format(tiemDate); //过滤不需要读取的短信的发送号码,博主这里用的是关键词过滤,小伙伴们也可以用电话号去过滤 if (content.contains("***")&&content.contains("****") &&content.contains("***")) { //从短信内容中获取验证码 String code=getCode(content,6); //回调数据 mMessageListener.onReceived(code); abortBroadcast(); } } } } //回调接口 public interface MessageListener { public void onReceived(String message); } public void setOnReceivedMessageListener(MessageListener messageListener) { this.mMessageListener = messageListener; } public static String getCode(String body, int YZMLENGTH) { // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的YZMLENGTH位数字字母组合 // (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字 // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现 // 获得数字字母组合 // Pattern p = Pattern .compile("(?<![0-9])([a-zA-Z0-9]{" + YZMLENGTH + "})(?![a-zA-Z0-9])"); // 获得纯数字 Pattern p = Pattern.compile("(?<![0-9])([0-9]{" + YZMLENGTH+ "})(?![0-9])"); Matcher m = p.matcher(body); if (m.find()) { System.out.println(m.group()); return m.group(0); } return null; } }
至此我们短信的广播接收器就完成了。
之后我们需要完成注册广播接收器以及填写验证码的代码,完成代码如下:
private void initSmsReader(){ public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; //生成广播处理 mSMSBroadcastReceiver = new SMSBroadcastReceiver(); //实例化过滤器并设置要过滤的广播 IntentFilter intentFilter = new IntentFilter(SMS_RECEIVED_ACTION); //设置优先级 intentFilter.setPriority(Integer.MAX_VALUE); //注册广播 this.registerReceiver(mSMSBroadcastReceiver, intentFilter); mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() { @Override public void onReceived(String message) { //在相应的编辑框中填写验证码 passCode.setText(message); } }); } @Override protected void onStart() { super.onStart(); initSmsReader(); } @Override protected void onDestroy() { super.onDestroy(); //注销短信监听广播 this.unregisterReceiver(mSMSBroadcastReceiver); }
至此我们自动填写验证码的功能就实现了。