时间:2020-11-23 12:11:27 | 栏目:Android代码 | 点击:次
先说一句:MIUI请放弃治疗!这里给个传送门:
识别短信验证码并提取还是挺常见的一个需求。所要解决的问题主要有:
1、如何监听
2、如何提取短信中的验证码
3、监听多次调用问题
直接看下面代码吧,很明了。需要注意的点有就是onChange会多次调用。其实打Log就看的出了,收到一条短信会调用两次onChange,Log结果如下:
mUri===content://sms/raw/20 mUri===content://sms/inbox/20
安卓7.0以上系统,点击标记为已读,也会调用一次
mUri===content://sms
收到一条短信都是uri后面都会有确定的一个数字,对应数据库的_id,比如上面的20
public static class SMSCodeObserver extends ContentObserver { private Activity mActivity; private static final String TAG = "SMSCodeObserver"; private SMSCodeListener mSMSCodeListener; private Uri mUri; public void setSMSCodeListener(SMSCodeListener SMSCodeListener) { mSMSCodeListener = SMSCodeListener; } public interface SMSCodeListener { void onResult(String code); } public SMSCodeObserver(Handler handler, Activity activity) { super(handler); mActivity = activity; } public void register() { mActivity.getContentResolver().registerContentObserver( Uri.parse("content://sms/"), true, this); } public void unRegister() { mActivity.getContentResolver().unregisterContentObserver(this); } @Override public void onChange(boolean selfChange, Uri uri) { super.onChange(selfChange, uri); if (uri == null) { mUri = Uri.parse("content://sms/inbox"); } else { mUri = uri; } if (mUri.toString().contains("content://sms/raw") || mUri.toString().equals("content://sms")) { return; } LogUtils.d(TAG, "mUri===" + mUri.toString()); AndPermission.with(mActivity) .permission(Manifest.permission.READ_SMS) .requestCode(100) .callback(this) .rationale(new RationaleListener() { @Override public void showRequestPermissionRationale(int requestCode, Rationale rationale) { AndPermission.rationaleDialog(mActivity, rationale) .show(); } }) .start(); } @PermissionYes(100) @SuppressWarnings("unused") private void getPermissionYes(List<String> grantedPermissions) { handleSMS(); } @PermissionNo(100) @SuppressWarnings("unused") private void getPermissionNo(List<String> deniedPermissions) { if (AndPermission.hasPermission(mActivity, Manifest.permission.READ_SMS)) { handleSMS(); } else { AndPermission.defaultSettingDialog(mActivity) .show(); } } private void handleSMS() { /* 按照日期倒序排序 */ Cursor cursor = mActivity.getContentResolver().query(mUri, null, null, null, "date desc"); if (cursor != null) { if (cursor.moveToFirst()) {//游标移动到first位置 /* 发件人的号码 */ String address = cursor.getString(cursor.getColumnIndex("address")); /* 短信内容 */ String body = cursor.getString(cursor.getColumnIndex("body")); LogUtils.d(TAG, "address:" + address + ",body:" + body); if (!body.contains("验证码")) { return; } /* 利用正则提取验证码(根据实际情况修改) */ String code = getSMSCode(body); if (code != null) { if (mSMSCodeListener != null) { mSMSCodeListener.onResult(code); } LogUtils.d(TAG, "code:" + code); } } cursor.close(); } } private static String getSMSCode(String msg) { /*提取正则表达式,需按需修改*/ Pattern p = Pattern.compile("(?<![0-9])([0-9]{6})(?![0-9])"); Matcher m = p.matcher(msg); if (m.find()) { LogUtils.d(TAG, m.group()); return m.group(0); } return null; } }