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

Prerequisites---permissions

<uses-permissionAndroid:name= "Android.permission.SEND_SMS"></uses-permission><uses-permissionAndroid:name= "Android.permission.RECEIVE_SMS"></uses-permission> <uses-permissionAndroid:name= "Android.permission.READ_SMS"></uses-permission>

  1. send a text message and prompt for a successful delivery and whether the recipient is receiving

     Packagecom.javen.utils;Importjava.util.ArrayList;Importandroid.app.Activity;Importandroid.app.PendingIntent;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.content.IntentFilter;ImportAndroid.telephony.SmsManager;ImportAndroid.widget.Toast;/** * @authorJaven **/ Public classSendmessageutil {/**send and receive broadcasts **/    Private StaticString sent_sms_action = "Sent_sms_action"; Private StaticString delivered_sms_action = "Delivered_sms_action"; /*** Implement SMS *@paramContext *@paramtext text message content *@paramPhoneNumber 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 () > 70) {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, "Recipient succeeds", Toast.length_long). Show (); }    };}


  2. Get SMS content via SMS database

     PackageCom.example.message;ImportJava.util.regex.Matcher;ImportJava.util.regex.Pattern;Importandroid.app.Activity;ImportAndroid.content.ContentResolver;ImportAndroid.content.Context;ImportAndroid.database.ContentObserver;ImportAndroid.database.Cursor;ImportAndroid.net.Uri;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {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 TypeString where = "date >" + (System.currenttimemillis ()-10 * 60 * 1000); 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 (">>>>>>>>>>>>>>>> Contact Name list:" +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 (); }    classSmsobserverextendsContentobserver { PublicSmsobserver (Context context, Handler Handler) {Super(handler); } @Override Public voidOnChange (BooleanSelfchange) {            Super. OnChange (Selfchange); //whenever a new message arrives, use our method of getting a short messageGetsmsfromphone (); }    }}

    SMS main structure:
      
    _ID: SMS number, such as 100
      
    THREAD_ID: The serial number of the conversation, such as 100, with the same mobile phone number of each other SMS, its serial number is the same
      
    Address: The sender's location, which is the phone number, such as +86138138000
      
    Person: sender, if the sender is a specific name in the Address book, The Stranger is null
      
    Date: Dates, long type, such as 1346988516, can be set for date display format
      
    Protocol: Protocol 0sms_rpoto SMS, 1mms_proto MMS
      
    READ: Reading 0 unread, 1 read
      
    Status: SMS state-1 Receive, 0complete,64pending,128failed
      
    Type: SMS Type 1 is received, 2 is issued
      
    Body: Text Message specific content
      
    Service_center: SMS Service center number, such as +8613800755500


    The 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

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.