How Android realizes receiving and sending SMS _android

Source: Internet
Author: User
Tags gettext sendmsg

Each cell phone has a message to receive and send the function, below we through the code to realize receive and send the message function.

First, receive SMS

1, the creation of internal broadcast receiver class, the receiving system sent SMS broadcast
2, from the content of the text to resolve the message sender and SMS content
3. Registering the broadcast in the activity
4, to add the right to receive SMS

Put the code below.
Activity_main.xml file to display SMS Sender number and display 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 "/> &L T TextView android:id= "@+id/sms_from_txt" android:layout_width= "wrap_content" android:layout_height= "20DP" a ndroid:layout_marginleft= "15DP" android:layout_torightof= "@id/sms_from"/> <textview android:id= "@+id/sms_c
    Ontent "android:layout_width=" wrap_content "android:layout_height=" 20DP "android:layout_below=" @id/sms_from "
    android:layout_margintop= "20DP" android:text= "Content"/> <textview android:id= "@+id/sms_content_txt" Android:layout_width= "Wrap_content" android:layout_height= "20DP" android:layout_marginleft= "15DP" android:l Ayout_margintop= "20DP" android:layout_below= "@id/sms_from_txt" android:layout_torightof= "@id/sms_content"/> </RelativeLayout>

 

Mainactivity.java file

public class Mainactivity extends Appcompatactivity {private TextView FROMTV;

  Private TextView Contenttv;
  Private Intentfilter Intentfilter;

  Private Messagereceiver Messagereceiver;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

    Setcontentview (R.layout.activity_main);
    Initview ();
  Getsms ();                 private void Getsms () {intentfilter = new intentfilter ();
    Intentfilter.addaction ("Android.provider.Telephony.SMS_RECEIVED");
    Messagereceiver = new Messagereceiver ();
    Set higher priority intentfilter.setpriority (100);
  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 message object[] PDUs = (object[]) bundle.get ("PDUs");
      smsmessage[] messages = new Smsmessage[pdus.length];
      for (int i = 0; i < messages.length i++) {Messages[i] = SMSMESSAGE.CREATEFROMPDU ((byte[)) pdus[i]);

      //Get the sender number String address = messages[0].getoriginatingaddress ();
      String fullmessage = "";
      for (Smsmessage message:messages) {//Get SMS content Fullmessage + = Message.getmessagebody ();
      //Truncate the broadcast to prevent it from continuing to receive Abortbroadcast () from the SMS program brought by Android;
      Fromtv.settext (address);
    Contenttv.settext (Fullmessage);

 }
  }
}

Note: registered broadcast receivers must be unregistered in the OnDestroy () method.

Because SMS broadcasts are ordered broadcasts, we can prioritize our own receivers if we don't want Android's own SMS program to receive text messages, and then truncate the broadcast after we've received the broadcast, preventing it from being received by Android's own SMS program.

Second, send SMS

1, get the receiver's number and SMS content
2, get SMS Send management Example
3, constructs the pendingintent to start the short note sends the state to monitor the broadcast
4. Call Send SMS function, send text message by incoming parameter
5, constructs the broadcast receiver internal class monitoring message whether sends the success
6, obtain the broadcast receiver instance and Intentfilter instance, registers the broadcast receiver
7, in OnDestroy () cancellation of the registered broadcast receiver
8, in the Androidmanifest.xml file to add text message to 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= "match_parent"
    android:layout_height= "50DP"
    android:hint= "to"/>
  <edittext
    android:id= "@+id/to_content"
    Match_parent "
    android:layout_height=" 50DP "
    android:layout_below=" @id/to_ed "
    android:hint=" Content "/>
  <button
    android: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 {private context context;
  Private EditText Toedit;
  Private EditText tocontent;
  Private Intentfilter Sendfilter;
  Private Sendstatusreceiver 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 the click of the Send button to listen to the event button sendmsg = (Button) Findviewbyid (r.id.send_msg);
  Sendmsg.setonclicklistener (this); @Override public void OnClick (view view) {switch (View.getid ()) {case R.id.send_msg:sendmessage
       ();
      Break
    Default:break;
    } private void SendMessage () {//Get SMS Receiver number String to = Toedit.gettext (). toString ();
   Get Send SMS Content String content = Tocontent.gettext (). toString ();
    Get broadcast receiver instance and Intentfilter instance Sendstatusreceiver = new Sendstatusreceiver ();
    Sendfilter = new Intentfilter ();
    Sendfilter.addaction ("Sent_sms_action");
    Registered broadcast monitoring Registerreceiver (Sendstatusreceiver, Sendfilter);
    Construction pendingintent Start SMS Send status monitor broadcast Intent sendintent = new Intent ("Sent_sms_action");
    pendingintent pi = pendingintent.getbroadcast (context, 0, sendintent, 0);

    Get SMS Management instance Smsmanager Smsmanager = Smsmanager.getdefault (); Call Send SMS function, incoming parameter 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 monitor SMS whether Send success */class Sendstatusreceiver extends broadcastreceiver{@Override Public v OID 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 broadcast Unregisterreceiver (sendstatusreceiver);

 }
}

Add SMS to the Androidmanifest.xml file to send the permission
<uses-permission android:name= "Android.permission.SEND_SMS"/>

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.