To achieve automatic acquisition of mobile phone SMS Verification Code, the principle of monitoring the text message database changes to parse text messages, get verification code.
Directly attach the code:
1. Create a class that listens to a 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 SMS database, automatically get SMS verification code * * @author Jaya * @date 2015-3-25 * */public class Autogetcode Ext Ends 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 SMS for the specified number in the Inbox cursor = Activity.managedquery (Uri.parse ("Content://sms/inbox"), new string[] {"_i D "," Address "," read "," Body "}," address=? " And read=? ", new string[] {" You want to intercept the phone number "," 0 "}," _id desC "); Sort by SMS ID, if you sort by date, the text you read is not allowed if you change your phone's time (cursor! = NULL && cursor.getcount () > 0) {curso R.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 To display the verification code of the EditText //Register SMS Change monitor this.getcontentresolver (). Registercontentobserver ( uri.parse ("content:/ /sms/"), true, Autogetcode);
3. Cancel the registration at the right place
@Override protected void OnDestroy () { //TODO auto-generated method Stub Super.ondestroy (); This.getcontentresolver (). Unregistercontentobserver (Autogetcode); }
4. Don't forget to add permissions at the end
<!--permission to read and write text messages-- <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 "/>
That's all you can do.
Resources:
Http://blog.sina.com.cn/s/blog_87dc03ea0101dvus.html
Http://www.it165.net/pro/html/201406/15300.html
Android automatically read SMS verification code