Android automatically reads the SMS verification code and android SMS Verification Code
The system automatically obtains the SMS verification code of the mobile phone. The principle is to parse the SMS and obtain the verification code by listening to the changes in the SMS database.
Directly attach the Code:
1. Create a class for listening to the database
Import java. util. regex. matcher; import java. util. regex. pattern; import android. app. activity; import android. database. contentObserver; import android. database. cursor; import android.net. uri; import android. OS. handler; import android. widget. editText;/*** listen to the SMS database and automatically obtain the SMS Verification Code ** @ author Jia yaguang * @ date 2015-3-25 **/public class AutoGetCode extends ContentObserver {private Cursor cursor = null; private Activity Activity; private String smsContent = ""; private EditText editText = null; public AutoGetCode (Activity activity, Handler handler, EditText edittext) {super (handler); this. activity = activity; this. editText = edittext;} @ Override public void onChange (boolean selfChange) {super. onChange (selfChange); // read the text message cursor = activity of the specified number in the inbox. managedQuery (Uri. parse ("content: // sms/inbox"), new String [] {"_ Id", "address", "read", "body"}, "address =? And read =? ", New String [] {" the phone number you want to intercept "," 0 "}," _ id desc "); // sort by SMS id, if the messages are sorted by date, the if (cursor! = Null & cursor. getCount ()> 0) {cursor. moveToFirst (); if (cursor. moveToFirst () {String smsbody = cursor. getString (cursor. getColumnIndex ("body"); String regEx = "(? <! [0-9]) ([0-9] {"+ 6 + "})(?! [0-9]) "; Pattern p = Pattern. compile (regEx); Matcher m = p. matcher (smsbody. toString (); while (m. find () {smsContent = m. group (); editText. setText (smsContent );}}}}}
2. Register in activity when using
AutoGetCode autoGetCode = new AutoGetCode (RegistCode. this, new Handler (), regist_code); // regist_code the EditText to display the verification code // listen for registered SMS changes this. getContentResolver (). registerContentObserver (Uri. parse ("content: // sms/"), true, autoGetCode );
3. cancel registration at the right place
@Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); this.getContentResolver().unregisterContentObserver(autoGetCode); }
4. Do not forget to add permissions.
<! -- Read and write sms permission --> <uses-permission android: name = "android. permission. RECEIVE_SMS "/> <uses-permission android: name =" android. permission. READ_SMS "/> <uses-permission android: name =" android. permission. SEND_SMS "/> <uses-permission android: name =" android. permission. WRITE_SMS "/>
In this way, you can.
References:
Http://blog.sina.com.cn/s/blog_87dc03ea0101dvus.html
Http://www.it165.net/pro/html/201406/15300.html