Android|自动填入短信验证码

这段时间太忙了,以至于一直没有时间更新博客。正好今天公司项目需要加入自动识别验证码的功能,所以特此记录一下
现在几乎任何App注册都离不开手机号,如果选择使用手机号注册,必定会接收并填入验证码进行注册。一些注重用户体验的App会在收到验证码后自动帮用户填入,免去了用户手动输入验证码的烦恼,整个注册过程用户是非常Happy的。
下面我们来实现这个功能,其实逻辑流程很简单:
  1. 创建广播接收器,拦截短信
  2. 判断是不是本应用需要的验证码短信,若是便继续,否则忽略
  3. 提取验证码,通过回调接口返回给Activity/Fragment
第一步:创建广播接收器 由于我们只需要在注册界面对短信进行拦截,因此采用动态注册的方式。首先编写广播接收器:
public class SMSBroadcastReceiver extends BroadcastReceiver {public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; //回调接口 private OnAuthCodeReceiver mOnAuthCodeReceiver; //利用正则表达式预编译功能 private static final Pattern AUTH_CODE_PATTERN = Pattern.compile("\\d{6}"); //识别是否是本APP需要的验证码短信的关键字 private final String SMS_KEYWORD = "小猪科技"; @Override public void onReceive(Context context, Intent intent) { if (SMS_RECEIVED_ACTION.equals(intent.getAction()) && intent.getExtras() != null) { Object[] pdus = (Object[]) intent.getExtras().get("pdus"); String format = intent.getStringExtra("format"); SmsMessage smsMessage = null; for (Object pdu : pdus) { if (Build.VERSION.SDK_INT < 23) { smsMessage = SmsMessage.createFromPdu((byte[]) pdu); } else { smsMessage = SmsMessage.createFromPdu((byte[]) pdu, format); } } if (smsMessage == null) { return; } String content = smsMessage.getDisplayMessageBody(); if (content.contains(SMS_KEYWORD) && mOnAuthCodeReceiver != null) { mOnAuthCodeReceiver.onReceiver(getAuthCode(content)); abortBroadcast(); } } }private String getAuthCode(String content) { Matcher matcher = AUTH_CODE_PATTERN.matcher(content); if (matcher.find()) { return matcher.group(); } else { return ""; } }public void setOnAuthCodeReceiverListener(OnAuthCodeReceiver receiver) { this.mOnAuthCodeReceiver = receiver; }public interface OnAuthCodeReceiver { void onReceiver(String code); } }

以上代码都是一些常规获取短信内容的操作,没有什么技术含量,唯一注意一下就是这个正则获取的是6位数的验证码。
第二步:动态注册广播 在注册界面,动态注册广播,并在注册界面销毁时,解除注册:
public class RegisterActivity extends AppCompatActivity { private EditText etAuthCode; private SMSBroadcastReceiver mSMSBroadcastReceiver = new SMSBroadcastReceiver(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); etAuthCode = findViewById(R.id.et_auth_code); registerSMSReceiver(); }private void registerSMSReceiver() { IntentFilter intentFilter = new IntentFilter(SMSBroadcastReceiver.SMS_RECEIVED_ACTION); intentFilter.setPriority(Integer.MAX_VALUE); registerReceiver(mSMSBroadcastReceiver, intentFilter); mSMSBroadcastReceiver.setOnAuthCodeReceiverListener( code -> etAuthCode.setText(code) ); }@Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mSMSBroadcastReceiver); } }

【Android|自动填入短信验证码】最后别忘了在清单文件中加入权限:

    推荐阅读