SoFunction
Updated on 2025-03-11

Android SMS verification code monitoring method to solve multiple calls onChange

Let me say first: MIUI please give up treatment! Here is a portal:

The pitfalls of MIUI notification text message permissions

It is a common requirement to identify SMS verification codes and extract them. The main problems to be solved are:

1. How to monitor

2. How to extract verification codes from SMS

3. The problem of listening multiple calls

Just look at the following code, it's very clear. One thing to note is that onChange will be called multiple times. In fact, you can see it by clicking Log. When you receive a text message, you will call onChange twice. The log result is as follows:

mUri===content://sms/raw/20
mUri===content://sms/inbox/20

Android 7.0 or above system, click mark as read and will also be called once.

mUri===content://sms

When you receive a text message, there will be a certain number after the uri, corresponding to the database _id, such as the above 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() {
      ().registerContentObserver(
          ("content://sms/"), true, this);
    }

    public void unRegister() {
      ().unregisterContentObserver(this);
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
      (selfChange, uri);
      if (uri == null) {
        mUri = ("content://sms/inbox");
      } else {
        mUri = uri;
      }
      if (().contains("content://sms/raw") || ().equals("content://sms")) {
        return;
      }
      (TAG, "mUri===" + ());
      (mActivity)
          .permission(.READ_SMS)
          .requestCode(100)
          .callback(this)
          .rationale(new RationaleListener() {
            @Override
            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
              (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 ((mActivity, .READ_SMS)) {
        handleSMS();
      } else {
        (mActivity)
            .show();
      }
    }

    private void handleSMS() {

       /* Sort by date in reverse order */
      Cursor cursor = ().query(mUri, null, null, null, "date desc");
      if (cursor != null) {
        if (()) {//Cursor moves to first position          /* Sender's number */
          String address = (("address"));
          /* SMS content */
          String body = (("body"));
          (TAG, "address:" + address + ",body:" + body);
          if (!("Verification Code")) {
            return;
          }

          /* Use regular extraction of verification code (modify according to actual situation) */
          String code = getSMSCode(body);
          if (code != null) {
            if (mSMSCodeListener != null) {
              (code);
            }
            (TAG, "code:" + code);
          }
        }
        ();
      }
    }

    private static String getSMSCode(String msg) {
      /* Extract regular expressions and need to be modified as needed*/
      Pattern p = ("(?<![0-9])([0-9]{6})(?![0-9])");
      Matcher m = (msg);
      if (()) {
        (TAG, ());
        return (0);
      }
      return null;
    }
  }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.