SoFunction
Updated on 2025-03-11

Android automatic filling of SMS verification code function (demo)

Project requirements:

In Android development, users will use the SMS verification function when logging in. If users are asked to view the SMS first and then return to the interface to fill in the verification code, the user experience is not very good, and sometimes it is necessary to realize the automatic filling function of the verification code.

practice:

My previous approach was to create a broadcast receiver first, accept broadcasts with changes in SMS, and then extract the verification code when receiving the broadcast.

At that time, a user test reported that his phone had installed some other SMS applications or that the phone itself had restricted permissions, this method might not work. Even if the priority is set at a high level, it cannot guarantee that other applications will not be taken first.

In the past, users did not investigate after uninstalling third-party software.

Now it is found that it can be implemented by listening to the SMS database. The monitoring of SMS database is mainly done through the ContentObserver class. ContentObserver mainly monitors the table of specific Databases through Uri, and will trigger it when the Uri observed by ContentObserver changes. ContentObserver content observers can monitor and observe changes in database items pointed to by a specific Uri, and then perform corresponding processing.

public class MessageContentObserver extends ContentObserver {
  private Context mContext; 
  private Handler mHandler; 
  private String code; 
  public MessageContentObserver(Context context, Handler handler) {    
    super(handler);
    mContext = context;
    mHandler = handler;
  }  
  /**
    * Callback function, when the monitored Uri changes, it will call back the method
    * It should be noted that when you receive a text message, it will call back twice
    * When receiving text messages, you usually execute the onchange method twice. The first time you usually use raw.
    * Although I received the text message. The text message was not written to the inbox
    */
  @Override
  public void onChange(boolean selfChange, Uri uri) {   
    if (().equals("content://sms/raw")) {     
     return;
    }    
   Uri inboxUri = ("content://sms/inbox");   
   Cursor c = ().query(inboxUri, null, null, null, "date desc"); // Sort SMS database in chronological order    if (c != null) {      
       if (()) {       
         String address = (("address"));//Sender number         String body = (("body")); // SMS content        if (!("10086")) {      
            return;
        }        
        Pattern pattern = ("(\\d{6})");//Regular expression matching verification code        Matcher matcher = (body);        if (()) {
          code = (0);          
          Message msg = ();
           = MainActivity.MSG_RECEIVE_CODE;
           = code;
          (msg);
        }
      }
      ();
    }
  }
}

Called:

/**
  * Implementation of automatic filling function of SMS verification code
  */
public class MainActivity extends Activity { 
  public static final int MSG_RECEIVE_CODE = 1; //Received the verification code of the text message  private EditText codeEdt; //Input box of SMS verification code  private MessageContentObserver messageContentObserver;  //Callback interface  @SuppressLint("HandlerLeak")
  Handler handler = new Handler() {    
  @Override
  public void handleMessage(Message msg) {   
   if ( == MSG_RECEIVE_CODE) {
       //Set the read content      }
    }
  };  
  @Override
  protected void onCreate(Bundle savedInstanceState) {   
    (savedInstanceState);
    setContentView(.activity_main);
    codeEdt = (EditText) findViewById();
    findViewById(.send_sms_btn).setOnClickListener(new () {    
      @Override
      public void onClick(View v) {
        senSMSCode();
      }
    });
    messageContentObserver = new MessageContentObserver(, handler);
 getContentResolver().registerContentObserver(("content://sms/"), true, messageContentObserver);
  }  
   /**
    * Cancel registration
    */
  @Override
  protected void onDestroy() {   
    ();
 getContentResolver().unregisterContentObserver(messageContentObserver);
  }  
  private void senSMSCode() {
  }
}

Need to add permissions

<!--Permission to read text messages-->
  <uses-permission android:name=".RECEIVE_SMS"/>
  <uses-permission android:name=".READ_SMS" />

Regarding the content://sms/inbox table, the roughly contained fields are:

_id | short message serial number such as 100 thread_id | dialogue serial number such as 100
address | Sender address, mobile phone number. For example +8613811810000 person | Sender, return a number that is the serial number in the contact list, strangers are null
date | Date long type. For example, 1256539465022 protocol | protocol 0 SMS_RPOTO, 1 MMS_PROTO
read | read 0 not read, 1 read
status | Status -1 Receive, 0 complete, 64 pending, 128 failed
type | Type 1 is received, 2 is sent
body | short message content
service_center | SMS service center number number.
content://sms/inbox Inbox
content://sms/sent sent
content://sms/draft draft
content://sms/outbox Outbox (information being sent)
content://sms/failed failed to send
content://sms/queued list to be sent

Project gallery

/88ios/SMSContentObserver-master

The project mainly uses third-party bombs to send text messages. If you are interested, you may wish to take a look.

The above is the Android automatic message verification code function introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!