当前位置:主页 > 移动开发 > Android代码 >

Android自动获取短信验证码功能

时间:2022-03-29 09:14:47 | 栏目:Android代码 | 点击:

先给大家展示下效果图,如果大家感觉不错,请参考实现代码。

1.自定义监听类

/**
 * 短信监听器,用于自动填充验证码
*/
public class SMSContentObserver extends ContentObserver {
  public final String SMS_URI_INBOX = "content://sms/inbox";//收信箱
  private Activity activity = null;
  private String smsContent = "";//验证码
  private EditText verifyText = null;//验证码编辑框
  private String SMS_ADDRESS_PRNUMBER = "10690329013589";//短息发送提供商
  private String smsID = "";
  //短信观察者 收到一条短信时 onchange方法会执行两次,所以比较短信id,如果一致则不处理
  public SMSContentObserver(Activity activity, Handler handler, EditText verifyText) {
    super(handler);
    this.activity = activity;
    this.verifyText = verifyText;
  }
  @Override
  public void onChange(boolean selfChange) {
    super.onChange(selfChange);
    Cursor cursor = null;// 光标
    // 读取收件箱中指定号码的短信
    cursor = activity.getContentResolver().query(Uri.parse(SMS_URI_INBOX),
      new String[]{"_id", "address", "body", "read"}, //要读取的属性
      "address=? and read=?", //查询条件是什么
      new String[]{SMS_ADDRESS_PRNUMBER, "0"},//查询条件赋值
      "date desc");//排序
    if (cursor != null) {
      cursor.moveToFirst();
      if (cursor.moveToFirst()) {
        //比较和上次接收到短信的ID是否相等
        if (!smsID.equals(cursor.getString(cursor.getColumnIndex("_id")))) {
          String smsbody = cursor.getString(cursor.getColumnIndex("body"));
          //用正则表达式匹配验证码
          Pattern pattern = Pattern.compile("[0-9]{6}");
          Matcher matcher = pattern.matcher(smsbody);
          if (matcher.find()) {//匹配到6位的验证码
            smsContent = matcher.group();
            if (verifyText != null && null != smsContent && !"".equals(smsContent)) {
              verifyText.requestFocus();//获取焦点
              verifyText.setText(smsContent);//设置文本
              verifyText.setSelection(smsContent.length());//设置光标位置
            }
          }
          smsID = cursor.getString(cursor.getColumnIndex("_id"));
        }
      }
    }
  }
}

2.在登录页面事件化监听类

//实例化短信监听器
SMSContentObserver mObserver = new SMSContentObserver(getActivity(), new Handler(), mEt_auth_code);
// 注册短信变化监听
mContext.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, mObserver);

3.声明读取短信权限

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />

4.为了防止内存泄漏,记得注销监听

@Override
public void onDestroy() {
super.onDestroy();
  //注销短信监听   
  mContext.getContentResolver().unregisterContentObserver(mObserver);
} 

小结:

去短信库获取短信比较不容易被拦截

您可能感兴趣的文章:

相关文章