1. Custom listener class
/** *SMS** for autofill verification codes */ public class SMSContentObserver extends ContentObserver { public final String SMS_URI_INBOX = "content://sms/inbox";//Inbox private Activity activity = null; private String smsContent = "";//Verification code private EditText verifyText = null;//Verification code edit box private String SMS_ADDRESS_PRNUMBER = "10690329013589";//SMS provider private String smsID = ""; //When the SMS observer receives a SMS, the onchange method will be executed twice, so compare the SMS IDs, and if they are consistent, they will not be processed. 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 // Read text messages from the specified number in the inbox cursor = activity.getContentResolver().query(Uri.parse(SMS_URI_INBOX), new String[]{"_id", "address", "body", "read"}, //Attribute to be read "address=? and read=?", //What is the query condition new String[]{SMS_ADDRESS_PRNUMBER, "0"},//Query condition assignment "date desc");//sort if (cursor != null) { cursor.moveToFirst(); if (cursor.moveToFirst()) { //Compare to see if the ID of the last received SMS is equal if (!smsID.equals(cursor.getString(cursor.getColumnIndex("_id")))) { String smsbody = cursor.getString(cursor.getColumnIndex("body")); // Match the verification code with a regular expression Pattern pattern = Pattern.compile("[0-9]{6}"); Matches matches = pattern.matcher (smsbody); if (matcher.find()) {//match to 6-digit verification code smsContent = matcher.group(); if (verifyText != null && null != smsContent && !"".equals(smsContent)) { verifyText.requestFocus();//Get the focus verifyText.setText(smsContent);//Set the text verifyText.setSelection(smsContent.length());//Set the cursor position } } smsID = cursor.getString(cursor.getColumnIndex("_id")); } } } } }
2. Event listener class on login page
//Instantiate SMS** SMSContentObserver mObserver = new SMSContentObserver(getActivity(), new Handler(), mEt_auth_code); // Register SMS change listener mContext.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, mObserver);
3. Declare permission to read SMS messages
<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. In order to prevent memory leaks, remember to log out of the monitor
@Override public void onDestroy() { super.onDestroy (); //log out SMS monitor mContext.getContentResolver().unregisterContentObserver(mObserver); }
Summary:
Going to the SMS library to get text messages is less likely to be intercepted