SoFunction
Updated on 2025-03-11

Automatically fill in Android SMS verification code

Automatically fill in Android SMS verification code

1. Customize the Observer to monitor the changes in the SMS database (note that you add SMS permissions)

import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;

/**
 * Created by 001 on 17/3/22.
 */

public class SmsObserver extends ContentObserver {

  public static final String SMS_URI_INBOX = "content://sms/inbox";
  private Activity activity = null;
  private String smsContent = "";
  private SmsListener listener;

  public SmsObserver(Activity activity, Handler handler, SmsListener listener) {
    super(handler);
     = activity;
     = listener;
  }

  @Override
  public void onChange(boolean selfChange) {
    (selfChange);
    Cursor cursor = null;
    // Read text messages containing a keyword in your inbox    ContentResolver contentResolver = ();
    cursor = ((SMS_URI_INBOX), new String[] {
            "_id", "address", "body", "read" }, "body like ? and read=?",
        new String[] { "%Keyword%", "0" }, "date desc");
    if (cursor != null) {
      ();
      if (()) {
        String smsbody = cursor
            .getString(("body"));
        String regEx = "[^0-9]";
        Pattern p = (regEx);
        Matcher m = (());
        smsContent = ("").trim().toString();
        if (!(smsContent)) {
          (smsContent);
        }

      }
    }
  }

  /*
    * SMS callback interface
    */
  public interface SmsListener {
    /**
      * Accept sms status
      *
      * @Title: onResult
      */
    void onResult(String smsContent);
  }
}

2. Use:

SmsObserver smsObserver = new SmsObserver(this, new Handler(), new () {
      @Override
      public void onResult(String smsContent) {
 //Write according to your needs //For example:(smsContent);      }    });().registerContentObserver(("content://sms/"), true, smsObserver);


Thank you for reading, I hope it can help you. Thank you for your support for this site!