Android Receive and send SMS

Source: Internet
Author: User
Tags gettext sendmsg

Each cell phone has a text message receiving and sending function, below we through the code to achieve receiving and sending SMS functions.

One, receive SMS

1, create the internal broadcast receiver class, receive system issued by SMS broadcast
2, from the content to resolve the text message sender and SMS content
3. Registering the broadcast in the activity
4. Add Receive SMS Permission

Put the specific code below.

Activity_main.xml file for displaying SMS sender numbers and displaying SMS content

<?xml version= "1.0" encoding= "Utf-8"?><relativelayout xmlns:android="Http://schemas.android.com/apk/res/android" android:layout_width="Match_parent"android:layout_height="Match_parent" >            <textview  android:id  = "@+id/sms_from"  android:layout_width  = "wrap_content"  android:layout_height  = "20DP"  android:text  =" from "/>     <textview  android:id  = "@+id/sms_from_txt"  android:layout_width
      = "wrap_content"  android:layout_height  =         "20DP"  android:layout_marginleft  = "15DP"  android:layout_torightof  = "@id/sms_from" />     <textview  android:id  = "@+id/sms_content"  android:layout_width
      = "wrap_content"  android:layout_height  =         "20DP"  android:layout_below  = "@id/sms_from"  android:layout_margintop  = "20DP"  android:text  =/>     <TextViewandroid:id="@+id/sms_content_txt"android:layout_width=  "Wrap_content"android:layout_height="20DP"android:layout_marginleft="15DP"  android:layout_margintop="20DP"android:layout_below="@id/sms_from_ TXT "android:layout_torightof=" @id/sms_content "/>                                                        </relativelayout>

Mainactivity.java file

 Public  class mainactivity extends appcompatactivity {    PrivateTextView FROMTV;PrivateTextView Contenttv;PrivateIntentfilter Intentfilter;PrivateMessagereceiver Messagereceiver;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Initview ();    Getsms (); }Private void getsms() {Intentfilter =NewIntentfilter (); Intentfilter.addaction ("Android.provider.Telephony.SMS_RECEIVER"); Messagereceiver =NewMessagereceiver ();//Set a higher priorityIntentfilter.setpriority ( -);    Registerreceiver (Messagereceiver, Intentfilter); }Private void Initview() {FROMTV = (TextView) Findviewbyid (r.id.sms_from_txt);    Contenttv = (TextView) Findviewbyid (r.id.sms_content_txt); }@Override    protected void OnDestroy() {Super. OnDestroy ();    Unregisterreceiver (Messagereceiver); } class Messagereceiver extends Broadcastreceiver {@Override         Public void OnReceive(context context, Intent Intent) {Bundle bundle = Intent.getextras ();//Extract SMS MessagesObject[] PDUs = (object[]) Bundle.get ("PDUs"); smsmessage[] Messages =NewSmsmessage[pdus.length]; for(inti =0; i < messages.length; i++) {Messages[i] = SMSMESSAGE.CREATEFROMPDU ((byte[]) pdus[i]); }//Get Sender numberString address = messages[0].getoriginatingaddress (); String Fullmessage =""; for(Smsmessage message:messages) {//Get SMS contentFullmessage + = Message.getmessagebody (); }//Truncate the broadcast to prevent it from continuing to be received by an Android-brought SMS programAbortbroadcast ();            Fromtv.settext (address);        Contenttv.settext (Fullmessage); }    }}

Note: Registered broadcast receivers, be sure to unregister in the OnDestroy () method.

Since SMS broadcasts are orderly broadcasts, if we do not want the SMS program that comes with Android to receive SMS messages, we can set our own receiver priority, and then truncate the broadcast after we have received the broadcast, preventing it from being received by the Android-brought SMS program.

Second, send SMS

1. Get the recipient's number and SMS content
2. Receive SMS Management Example
3, constructs the pendingintent to initiate the SMS sends the status to monitor the broadcast
4, call send SMS function, incoming parameters send SMS
5, constructs the broadcast receiver internal class to monitor the text message whether sends the success
6. Obtain the broadcast receiver instance and Intentfilter instance, register the broadcast receiver
7. Unregistered broadcast receivers in OnDestroy ()
8, in the Androidmanifest.xml file to add SMS Send permission

Put the specific layout file and code below

Activity_send_msg.xml file

<?xml version= "1.0" encoding= "Utf-8"?><relativelayout xmlns:android="Http://schemas.android.com/apk/res/android" android:layout_width="Match_parent"android:layout_height="Match_parent" >            <edittext  android:id  = "@+id/to_ed"  android:layout_width  =< Span class= "Hljs-value" > "match_parent"  android:layout_height  = "50DP"  android:hint  = "to" />     <edittext  android:id  = "@+id/to_content"  android:layout_width  = "match_parent"  android:layout_height  = "50DP"  android:layout_below  = "@id/to_ed"  android:hint  =  "content" />     <buttonandroid:id="@+id/send_msg"android:layout_width="Match_ Parent "android:layout_height=" 50DP "android:layout_below=" @id/to_content "  Android:text="@string/send_message"/>                                        </relativelayout>

Sendmsgactivity.java file

 Public  class sendmsgactivity extends appcompatactivity  implements  View. Onclicklistener {    PrivateContext context;PrivateEditText Toedit;PrivateEditText tocontent;PrivateIntentfilter Sendfilter;PrivateSendstatusreceiver Sendstatusreceiver;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.LAYOUT.ACTIVITY_SEND_MSG); Context = This;    Initview (); }Private void Initview() {Toedit = (EditText) Findviewbyid (r.id.to_ed); Tocontent = (EditText) Findviewbyid (r.id.to_content);//Add click Listener Event for Send buttonButton sendmsg = (button) Findviewbyid (r.id.send_msg); Sendmsg.setonclicklistener ( This); }@Override     Public void OnClick(View view) {Switch(View.getid ()) { CaseR.id.send_msg:sendmessage (); Break;default: Break; }    }Private void SendMessage() {//Get SMS Recipient numberString to = Toedit.gettext (). toString ();//Get send SMS ContentString content = Tocontent.gettext (). toString ();//Get broadcast receiver instances and Intentfilter instancesSendstatusreceiver =NewSendstatusreceiver (); Sendfilter =NewIntentfilter (); Sendfilter.addaction ("Sent_sms_action");//Register for radio monitoringRegisterreceiver (Sendstatusreceiver, Sendfilter);//Construction pendingintent start SMS Send status Monitor broadcastIntent sendintent =NewIntent ("Sent_sms_action"); pendingintent pi = pendingintent.getbroadcast (context,0, Sendintent,0);//Get SMS Management examplesSmsmanager Smsmanager = Smsmanager.getdefault ();//Call send SMS function, incoming parameters send SMS (第一、三、四 parameter is receiver number, SMS content, SMS Send status monitor pendingintent)Smsmanager.sendtextmessage (To,NULL, Content, Pi,NULL); }/** * Construct broadcast receiver internal class monitoring text message is sent successfully * /Class Sendstatusreceiver extends broadcastreceiver{@Override         Public void OnReceive(context context, Intent Intent) {if(Getresultcode () = = RESULT_OK) {Toast.maketext (context,"Successful", Toast.length_short). Show (); }Else{Toast.maketext (context,"Failed", Toast.length_short). Show (); }        }    }@Override    protected void OnDestroy() {Super. OnDestroy ();//cancellation of registered broadcastsUnregisterreceiver (Sendstatusreceiver); }}

Add SMS to Androidmanifest.xml file

<uses-permission android:name="android.permission.SEND_SMS"/>

Android Receive and send SMS

Related Article

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.