General users like to use mobile phone number as a user name to register the app account, this is usually through the verification code of mobile phone verification, the following we study a very practical method, through the monitoring of SMS-SMS Verification code automatically fill in, improve the user experience.
First, let's look at how to listen to SMS.
First, to obtain the entire content of text messages
1. Create a new smsbroadcastreceiver:
PackageCom.example.messagecut;ImportJava.text.SimpleDateFormat;ImportJava.util.Date;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;ImportAndroid.content.Intent;ImportAndroid.telephony.SmsMessage;/** * Configure the Broadcast receiver: * <receiver android:name= ". Smsbroadcastreceiver "> * <intent-filter android:priority=" + "> * <action android:name=" ANDROID.P Rovider. Telephony.sms_received "/> * </intent-filter> * </receiver> * * NOTE: * <intent-filter Android:prio rity= "+" > means: * Set this broadcast receiver to the highest level */ Public class smsbroadcastreceiver extends broadcastreceiver { Private StaticMessageListener Mmessagelistener; Public Smsbroadcastreceiver() {Super(); }@Override Public void OnReceive(context context, Intent Intent) {Object [] pdus= (object[]). Intent.getextras (). Get ("PDUs"); for(Object Pdu:pdus) {Smsmessage SMSMESSAGE=SMSMESSAGE.CREATEFROMPDU (byte[]) PDU); String sender=smsmessage.getdisplayoriginatingaddress (); String Content=smsmessage.getmessagebody ();LongDate=smsmessage.gettimestampmillis (); Date timedate=NewDate (date); SimpleDateFormat simpledateformat=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Time=simpledateformat.format (timedate); System.out.println ("SMS from:"+sender); System.out.println ("message content:"+content); System.out.println ("SMS Time:"+time); mmessagelistener.onreceived (content);//If the text message comes from 5556 and no longer passes down, this number can be used as the SMS platform number. if("5556". Equals (Sender) {System.out.println ("Abort"); Abortbroadcast (); } } }//Callback interface Public interface messagelistener { Public void onreceived(String message); } Public void Setonreceivedmessagelistener(MessageListener MessageListener) { This. Mmessagelistener=messagelistener; }}
2. Configure the Androidmanifest.xml file:
<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android="Http://schemas.android.com/apk/res/android" package ="Com.example.messagecut"android:versioncode="1"android:versionname ="1.0" > <uses-sdkandroid:minsdkversion="8"android:targetsdkversion ="/>" <applicationandroid:allowbackup="true"android:icon="@drawable/ Ic_launcher "android:label=" @string/app_name "android:theme=" @style/apptheme " > <activityandroid:name=". Mainactivity "android:label=" @string/app_name " > <intent-filter> <action android:name="Android.intent.action.MAIN" /> <category android:name="Android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=". Smsbroadcastreceiver "> <intent-filter > <action android:name="Android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> </Application> <uses-permission android:name="Android.permission.RECEIVE_SMS"/> <uses-permission android:name="Android.permission.READ_SMS"/></manifest>
3. Create mainactivity.java-to receive the text message content displayed:
PackageCom.example.messagecut;ImportAndroid.os.Bundle;ImportAndroid.widget.TextView;ImportCom.example.messagecut.SMSBroadcastReceiver.MessageListener;Importandroid.app.Activity;/** * Demo Description: * Use Broadcastreceiver to implement listening SMS * * NOTE permission: * <uses-permission android:name= "android.permission.RECEIVE_ SMS "/> * * Details: * http://blog.csdn.net/lfdfhl/article/details/8195400 * * * * * Public class mainactivity extends Activity{ PrivateTextView Mtextview;PrivateSmsbroadcastreceiver Msmsbroadcastreceiver;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Init (); }Private void Init() {mtextview= (TextView) Findviewbyid (R.id.textview); Msmsbroadcastreceiver=NewSmsbroadcastreceiver (); Msmsbroadcastreceiver.setonreceivedmessagelistener (NewMessageListener () { Public void onreceived(String message) {mtextview.settext (message); } }); }}
4. layout file is simple, TextView is used to display text message content:
<relativelayout xmlns:android="Http://schemas.android.com/apk/res/android"xmlns:tools="Http://schemas.android.com/tools"Android:layout_width="Match_parent"android:layout_height="Match_parent"Android:paddingbottom="@dimen/activity_vertical_margin"android:paddingleft="@dimen/activity_horizontal_margin"android:paddingright="@dimen/activity_horizontal_margin"android:paddingtop="@dimen/activity_vertical_margin"tools:context="Com.example.messagecut.MainActivity"> <textview android:id="@+Id/textview"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"android:text="@string/hello_world"/></relativelayout>
5. Run the project on the real phone and then send a message with another phone to get the following:
Intercepted the text message content.
Second, intercept the verification code
The above implementation of the interception of all text messages, below we see how to intercept effective information-verification code. The principle should be simple to intercept part of a string in a string.
The algorithm is:
/** * Intercept consecutive 6-digit combinations ([0-9]{"+ 6 +"}) from a string to intercept six-bit numbers before and after assertions cannot appear numbers used to get dynamic passwords from text messages * * @param str * SMS Content * @return captured 6-bit dynamic password */ PublicStringGetdynamicpassword(String str) {//6 is the number of digits of the verification code is generally six bitsPattern Continuousnumberpattern = Pattern.compile ("(? <![ 0-9]) ([0-9]{"+6+"}) (?! [0-9]) "); Matcher m = continuousnumberpattern.matcher (str); String Dynamicpassword =""; while(M.find ()) {System.out.print (M.group ()); Dynamicpassword = M.group (); }returnDynamicpassword; }
In the mainactivity:
PackageCom.example.messagecut;ImportAndroid.os.Bundle;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportJava.util.regex.Matcher;ImportJava.util.regex.Pattern;ImportCom.example.messagecut.SMSBroadcastReceiver.MessageListener;Importandroid.app.Activity;/** * Demo Description: * Use Broadcastreceiver to implement listening SMS * * NOTE permission: * <uses-permission android:name= "android.permission.RECEIVE_ SMS "/> * * * * * * * * Public class mainactivity extends Activity{ PrivateEditText Mcode;PrivateSmsbroadcastreceiver Msmsbroadcastreceiver;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Init (); }Private void Init() {mcode= (EditText) Findviewbyid (R.id.et_code); Msmsbroadcastreceiver=NewSmsbroadcastreceiver (); Msmsbroadcastreceiver.setonreceivedmessagelistener (NewMessageListener () { Public void onreceived(String message) {Mcode.settext (Getdynamicpassword (message));//intercept 6-digit verification Code} }); }/** * Intercept consecutive 6-digit combinations ([0-9]{"+ 6 +"}) from a string to intercept six-bit numbers before and after assertions cannot appear numbers used to get dynamic passwords from text messages * * @param str * SMS Content * @return captured 6-bit dynamic password */ PublicStringGetdynamicpassword(String str) {//6 is the number of digits of the verification code is generally six bitsPattern Continuousnumberpattern = Pattern.compile ("(? <![ 0-9]) ([0-9]{"+6+"}) (?! [0-9]) "); Matcher m = continuousnumberpattern.matcher (str); String Dynamicpassword =""; while(M.find ()) {System.out.print (M.group ()); Dynamicpassword = M.group (); }returnDynamicpassword; }}
Here we also modified the Activity_main.xml file, changed TextView to EditText, because Android phone users may prohibit the app access to text messages should be supported by manual fill.
Test on the real machine, send:
Receive:
Super-hanging super practical functions, quickly introduced into your project to go, will greatly improve the user experience!
Favorite friends pay attention to me! Your attention and support is my motivation!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Combat Simple Tutorial-the 36th gun (listen to SMS-implementation of SMS Verification code automatically fill in)