Android send SMS and receive verification code

Source: Internet
Author: User

Recent project requirements need to send SMS and receive verification code and display the verification code in the input box the following is my record premise---Permissions<uses-permission android:name="Android.permission.SEND_SMS"></uses-permission><uses-permission android:name="Android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="Android.permission.READ_SMS"></uses-permission>1. Send a text message and prompt for a successful delivery and whether the recipient received the package Com.javen.utils;import Java.util.arraylist;import Android.app.activity;import Android.app.pendingintent;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.telephony.smsmanager;import Android.widget.Toast;/** * @author Javen **/ Public classSendmessageutil {/** Send and receive broadcasts **/    Private StaticString sent_sms_action ="sent_sms_action"; Private StaticString delivered_sms_action ="delivered_sms_action"; /** * To send SMS * @param context * @param text text message content * @param phonenumber mobile phone number*/     Public Static voidSendMessage (Context context, string text, String phonenumber) {Context.registerreceiver (Sendmessag E,NewIntentfilter (sent_sms_action)); Context.registerreceiver (receiver,NewIntentfilter (delivered_sms_action)); //Create the Sentintent parameterIntent sentintent =NewIntent (sent_sms_action); Pendingintent SENTPI= Pendingintent.getbroadcast (Context,0, Sentintent,0); //Create the Deilverintent parameterIntent deliverintent =NewIntent (delivered_sms_action); Pendingintent Deliverpi= Pendingintent.getbroadcast (Context,0, Deliverintent,0); Smsmanager Smsmanager=Smsmanager.getdefault (); //if the word count exceeds 5, it needs to be split into multiple SMS messages.        if(Text.length () > -) {ArrayList<String> msgs =smsmanager.dividemessage (text);  for(String msg:msgs) {smsmanager.sendtextmessage (PhoneNumber,NULL, MSG, SENTPI, Deliverpi); }        } Else{smsmanager.sendtextmessage (PhoneNumber,NULL, text, SENTPI, DELIVERPI); }    }    Private StaticBroadcastreceiver SendMessage =NewBroadcastreceiver () {@Override Public voidOnReceive (Context context, Intent Intent) {//determine if the text message was sent successfully            Switch(Getresultcode ()) { CaseActivity.RESULT_OK:Toast.makeText (Context,"SMS sent successfully", Toast.length_short). Show ();  Break; default: Toast.maketext (Context,"Send failed", Toast.length_long). Show ();  Break;    }        }    }; Private StaticBroadcastreceiver receiver =NewBroadcastreceiver () {@Override Public voidOnReceive (Context context, Intent Intent) {//the Fangcheng received a text message .Toast.maketext (Context,"The other receives success", Toast.length_long). Show (); }    };}
2. Get SMS content via SMS database package Com.example.message;import Java.util.regex.matcher;import Java.util.regex.Pattern; Import Android.app.activity;import Android.content.contentresolver;import Android.content.context;import Android.database.contentobserver;import Android.database.cursor;import Android.net.uri;import Android.os.Bundle; Import Android.os.handler;import android.widget.Toast; Public classMainactivity extends Activity {PrivateSmsobserver Smsobserver; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Smsobserver=NewSmsobserver ( This, Smshandler); Getcontentresolver (). Registercontentobserver (Sms_inbox,true, Smsobserver); } PublicHandler Smshandler =NewHandler () {//This is where callbacks can be done.//TODO Public voidhandlemessage (android.os.Message msg) {System. out. println ("Smshandler carried out ... .."); }; }; PrivateUri Sms_inbox = Uri.parse ("content://sms/"); Public voidGetsmsfromphone () {contentresolver CR=Getcontentresolver (); string[] Projection=NewString[] {"Body","Address"," Person"};//" _id", "Address",//"Person", "date" ,//the TypeStringwhere="Date >"+ (System.currenttimemillis ()-Ten* -* +); Cursor cur= Cr.query (Sms_inbox, projection,where,NULL,"Date desc"); if(NULL==cur)return; if(Cur.movetonext ()) {String number= Cur.getstring (Cur.getcolumnindex ("Address"));//Phone numberString name = cur.getstring (Cur.getcolumnindex (" Person"));//Contact person Name ListString BODY = cur.getstring (Cur.getcolumnindex ("Body")); System. out. println (">>>>>>>>>>>>>>>> phone Number:"+Number ); System. out. println (">>>>>>>>>>>>>>>> Name List of contact person:"+name); System. out. println (">>>>>>>>>>>>>>>> SMS Content:"+body); //here I'm going to get the verification code in my SMS service number ~ ~Pattern pattern = Pattern.compile ("[A-za-z0-9]{5}"); Matcher Matcher= Pattern.matcher (body);//String body= "Test verification Code 2346ds"; if(Matcher.find ()) {String res= Matcher.group (). SUBSTRING (0,5);//get the content of a text messageShowtoast (RES); System. out. println (RES); } } } protected voidshowtoast (String text) {Toast.maketext (mainactivity. This, text, Toast.length_long). Show (); } classSmsobserver extends Contentobserver { PublicSmsobserver (Context context, Handler Handler) {super (Handler); } @Override Public voidOnChange (Boolean selfchange) {Super.onchange (selfchange); //whenever a new message arrives, use our method of getting a short messageGetsmsfromphone (); }}} SMS main structure: _id: SMS serial number, such as thread_id: the serial number of the dialogue, such as 100, with the same mobile phone number of each other text messages, its serial number is the same address: the sender, that is, the phone number, such as+86138138000Person: sender, if the sender is a specific name in the Address book, the Stranger is null Date: date, long type, such as 1346988516, you can set the date Display format Protocol: Protocol 0sms_rpoto SMS, 1MMS_PR Oto MMS Read: Read 0 unread, 1 read status: SMS State-1 Receive, 0complete,64pending,128failed type: SMS Type 1 is received, 2 is issued body: SMS Specific content service_center: SMS Service center number, such as+8613800755500the detailed database files are as follows:

SMS Database Analysis

Table Structure Analysis:

Address: SMS Sender phone number

Person: Contact Number, if there is a contact in the phone book, displays the number, and no contact displays null.

READ: Reading status, 0 unread, 1 read

Body: SMS Content

Thread Table: Threads table

Datal: Date

Message_count: Number of lines sent by SMS

Snippet: Last SMS Content

READ: SMS Read status

Android send SMS and receive verification code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.