Android: Receive and send SMS

Source: Internet
Author: User
<span id="Label3"></p><p><p>8.2 Receiving and sending SMS</p></p><p><p></p></p><p><p>Sending and receiving text messages should be one of the most basic features of every cell phone, even if the old phone many years ago will have this feature, and Android as an excellent smartphone operating system, naturally, there is no support in this Regard. Each Android phone has a built-in SMS app that makes it easy to send and receive text messages, as shown in Figure 8.4.</p></p><p><p></p></p><p align="center"><p align="center">Figure 8.4</p></p><p><p></p></p><p><p>But as a developer, it's obviously not enough to just be content with it. You know, Android also provides a series of APIs that allow us to even receive and send text messages in our own applications. In other words, as long as you have enough confidence, you can fully implement a text messaging application to replace the Android system comes with the SMS app. So let's take a look at how you can receive and send text messages in your app.</p></p><p><p></p></p><p><p>8.2.1 Receive SMS</p></p><p><p></p></p><p><p>In fact, receiving text messages is mainly using the broadcasting mechanism we have studied in the 5th Chapter. When the phone receives a text message, the system emits a radio value of android.provider.Telephony.SMS_RECEIVED, which carries all the data associated with the text Message. Each application can listen to it in a broadcast receiver and then parse out the contents of the text message when it is Broadcast.</p></p><p><p>Let's practice it with a concrete example, creating a new smstest project, first modifying the Activity_</p></p><p><p>The code in Main.xml is as Follows:</p></p><p><p></p></p><p><p><strong><linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"</strong> <strong>android:layout_width= "match_parent" android:layout_height= "match_parent</strong> "</p></p><p><p><strong>android:orientation= "vertical" ></strong></p></p><p><p></p></p><p><p></p></p><p><p><strong><linearlayout android:layout_width= "match_parent"</strong></p></p><p><p></p></p><p><p></p></p><p><p></p></p><p><p><strong>android:layout_height= "50dp" ></strong></p></p><p><p></p></p><p><p></p></p><p><p><strong><textviewandroid:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_gravity= " Center_vertical "android:padding=" 10dp "android:text=" from: "/></strong></p></p><p><p></p></p><p><p><strong><textviewandroid:id= "@+id/sender" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "center_vertical"/></strong></p></p><p><p><strong></LinearLayout></strong></p></p><p><p></p></p><p><p></p></p><p><p><strong><linearlayoutandroid:layout_width= "match_parent" android:layout_height= "50dp" ></strong></p></p><p><p></p></p><p><p><strong><textviewandroid:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_gravity= " Center_vertical "android:padding=" 10dp "android:text=" Content: "/></strong></p></p><p><p></p></p><p><p><strong><textviewandroid:id= "@+id/content" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "center_vertical"/></strong></p></p><p><p><strong></LinearLayout></strong></p></p><p><p></p></p><p><p></p></p><p><p><strong></LinearLayout></strong></p></p><p><p>In this layout file, we placed two linearlayout below the root element to display two rows of Data. The first LinearLayout has two TextView to display the sender of the Sms. There are also two TextView in the second linearlayout, which are used to display the contents of a text Message.</p></p><p><p>next, Modify the code in mainactivity, and in the OnCreate () method, get the instance of two TextView, as Follows:</p></p><p><p></p></p><p><p><strong>public class Mainactivity extends Activity {</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>Private TextView sender;</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>Private TextView content;</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>protected void OnCreate (bundlesavedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( r.layout.activity_main);</strong></p></p><p><p><strong>Sender = (TextView) Findviewbyid (r.id.sender);</strong></p></p><p><p><strong>Content = (TextView) Findviewbyid (r.id.content);</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>}</strong></p></p><p><p>Then we need to create a broadcast receiver to receive SMS broadcasts from the SYSTEM. In mainactivity, the new Messagereceiver inner class inherits from broadcastreceiver, and the logic to get the SMS data is written in the OnReceive () method, as shown in the following code:</p></p><p><p></p></p><p><p><strong>public class Mainactivity extends Activity {</strong></p></p><p><p></p></p><p><p>......</p></p><p><p></p></p><p><p></p></p><p><p><strong>Class Messagereceiver extends Broadcastreceiver {</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>Public voidonreceive (context context, Intent Intent) {bundle bundle = Intent.getextras ();</strong></p></p><p><p><strong>object[] PDUs = (object[]) bundle.get ("pdus");//</strong> Extract SMS Messages</p></p><p><p><strong>smsmessage[] messages = new smsmessage[pdus.length];</strong></p></p><p><p><strong>for (int i = 0; i < messages.length; i++) {</strong></p></p><p><p><strong>messages[i] = SMSMESSAGE.CREATEFROMPDU ((byte[]) pdus[i]);</strong></p></p><p><p></p></p><p><p></p></p><p><p></p></p><p><p></p></p><p><p>Send party number</p></p><br clear="all"><p><p><strong>}</strong></p></p><p><p><strong>stringaddress = messages[0].getoriginatingaddress ();//</strong> Get Hair</p></p><p><p></p></p><p><p></p></p><p><p><strong>String fullmessage = "";</strong></p></p><p><p><strong>For (smsmessage message:messages) {</strong></p></p><p><p><strong>fullmessage+= message.getmessagebody ();//</strong> Get SMS Content</p></p><p><p></p></p><p><p><strong>} sender.settext (address); Content.settext (fullmessage);</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p><strong>}</strong></p></p><p><p><strong>}</strong></p></p><p><p>As you can see, we first remove a Bundle object from the Intent parameter and then use the PDU key to extract an SMS PDUs array, each of which represents an SMS Message. Then use Smsmessage's Createfrompdu () method to convert each PDU byte array to smsmessage object, call this Object's getoriginatingaddress () method to get to the sender number of the text message, call Getmessagebody () method can get to the content of the text message, and then each Smsmessage object in the text of the message to join together, formed a complete text message. finally, the acquired sender number and SMS content are displayed on the TEXTVIEW.</p></p><p><p>After completing the messagereceiver, we also need to register it to receive the SMS broadcast, the code is as Follows:</p></p><p><p>public <strong>class Mainactivityextends Activity {</strong></p></p><p><p></p></p><p><p><strong>Private TextView sender;</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>Private TextView content;</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>Private Intentfilter receivefilter;</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>Private Messagereceiver messagereceiver;</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>Protected voidoncreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( r.layout.activity_main);</strong></p></p><p><p><strong>Sender = (TextView) Findviewbyid (r.id.sender); Content = (TextView) Findviewbyid (r.id.content); receivefilter = new Intentfilter ();</strong></p></p><p><p><strong>Receivefilter.addaction ("android.provider.Telephony.SMS_RECEIVED");</strong></p></p><p><p><strong>Messagereceiver = new Messagereceiver ();</strong></p></p><p><p><strong>Registerreceiver (messagereceiver, receivefilter);</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p></p></p><p><p></p></p><p><p></p></p><p><p><strong>protected void OnDestroy () {</strong></p></p><p><p><strong>Super.ondestroy ();</strong></p></p><p><p><strong>Unregisterreceiver (messagereceiver);</strong></p></p><p><p><strong>}</strong></p></p><p><p>......</p></p><p><p><strong>}</strong></p></p><p><p>You should already be familiar with the code, using the technology of dynamic registration Broadcast. Register the Messagereceiver in the OnCreate () method, and then unregister it in the OnDestroy () method.</p></p><p><p>The code is almost done here, but in the end we need to give the program a permission to receive the text message, modify the code in the Androidmanifest.xml as Follows:</p></p><p><p></p></p><p><p><strong><manifestxmlns:android= "http://schemas.android.com/apk/res/android"</strong> <strong>package= "com.example.smstest"</strong></p></p><p><p><strong>android:versioncode= "1" android:versionname= "1.0" ></strong></p></p><p><p><strong><uses-permissionandroid:name= "android.permission.RECEIVE_SMS"/></strong></p></p><p><p>......</p></p><p><p><strong></manifest></strong></p></p><p><p>Now you can run the program, as shown in interface 8.5.</p></p><p><p></p></p><p align="center"><p align="center">Figure 8.5</p></p><p><p></p></p><p><p>When a text message arrives, the sender and content of the message is displayed on the Interface. But then again, we are using simulators, how can the simulator receive text messages? Don't worry, DDMS provides a very full analog ring</p></p><p><p>So that we do not need to pay for real SMS charges can also be simulated to send and receive SMS Scenes. Switch Eclipse to DDMS view, then click the Emulator Control switch card, where you can send a text message to the simulator, as shown in Figure 8.6.</p></p><p><p></p></p><p align="center"><p align="center">Figure 8.6</p></p><p><p></p></p><p><p>As can be seen, we specify the Sender's number is 556677, and fill in a text message content, and then click the Send button, so that the message sent Successfully. Then we immediately look at the Smstest program, as shown in result 8.7.</p></p><p><p></p></p><p align="center"><p align="center">Figure 8.7</p></p><p><p></p></p><p><p>You can see that the sender number and text message content are displayed to the interface, indicating that the function of receiving SMS has been successfully implemented.</p></p><p><p></p></p><p><p>8.2.2 Intercept SMS</p></p><p><p></p></p><p><p>Looking closely at Figure 8.7, you will notice that a notification icon appears in the system status bar, which is generated by the SMS program that comes with ANDROID. That is, when the text message arrives, not only our program will receive this text message, the system SMS program will also Receive. The same text message is repeated two times will result in a poor user experience, then there is no way to block the system SMS program receiving function?</p></p><p><p>When we learned the orderly broadcast in the front 5.3.2, we already knew that the delivery of the ordered broadcast could be truncated, and the message broadcast by the system was an orderly broadcast, so here's our answer Yes. Modify the code in the mainactivity as Follows:</p></p><p><p></p></p><p><p><strong>public class Mainactivity extends Activity {</strong></p></p><p><p>......</p></p><p><p><strong>@Override</strong></p></p><p><p><strong>protected void OnCreate (Bundle Savedinstancestate) {</strong></p></p><p><p>......</p></p><p><p><strong>Receivefilter = new Intentfilter (); Receivefilter.addaction ("android.provider.Telephony.SMS_RECEIVED"); receivefilter.setpriority (100);</strong></p></p><p><p><strong>Messagereceiver = new Messagereceiver ();</strong></p></p><p><p><strong>Registerreceiver (messagereceiver, receivefilter);</strong></p></p><p><p><strong>}</strong></p></p><p><p>......</p></p><p><p><strong>Class Messagereceiver extends Broadcastreceiver {</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>public void OnReceive (context context, Intent Intent) {</strong></p></p><p><p>......</p></p><p><p><strong>Abortbroadcast ();</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p><strong>}</strong></p></p><p><p><strong>}</strong></p></p><p><p>As you can see, the critical steps are only two steps. One is to improve the priority of the messagereceiver, so that it can be before the system SMS program to receive text messages Broadcast. The second is to call the Abortbroadcast () method in the OnReceive () method to abort the continuation of the broadcast Transmission.</p></p><p><p>Now rerun the program and send a text message to the simulator, when only our own program can receive this Message. After pressing the back key to close the program, the System's SMS program will again have the ability to receive text Messages.</p></p><p><p>Note that this feature must be used with caution, arbitrary interception of text messages may result in loss of important data, so you must first think clearly before intercepting this function is not what you want.</p></p><p><p></p></p><p><p>8.2.3 Send SMS</p></p><p><p></p></p><p><p>Here we continue to extend the smstest project, adding a text message to it. So let's write the layout file first, modify the code in Activity_main.xml as Follows:</p></p><p><p></p></p><p><p><strong><linearlayoutxmlns:android= "http://schemas.android.com/apk/res/android"</strong> <strong>android:layout_width= "match_parent" android:layout_height= "match_parent</strong> "</p></p><p><p><strong>android:orientation= "vertical" ></strong></p></p><p><p>......</p></p><p><p><strong><linearlayoutandroid:layout_width= "match_parent" android:layout_height= "50dp" ></strong></p></p><p><p><strong><textview</strong></p></p><p><p><strong>Android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "center_vertical "android:padding=" 10DP "</strong></p></p><p><p><strong>android:text= "to:"/></strong></p></p><p><p></p></p><p><p></p></p><p><p><strong><edittextandroid:id= "@+id/to" android:layout_width= "0dp" android:layout_height= "wrap_content" android:layout_ gravity= "center_vertical" android:layout_weight= "1"/></strong></p></p><p><p><strong></LinearLayout></strong></p></p><p><p></p></p><p><p></p></p><p><p><strong><linearlayoutandroid:layout_width= "match_parent" android:layout_height= "50dp" ></strong></p></p><p><p><strong><edittext</strong></p></p><p><p><strong>android:id= "@+id/msg_input" android:layout_width= "0dp"</strong></p></p><p><p></p></p><p><p></p></p><p><p></p></p><p><p><strong>android:layout_height= "wrap_content" android:layout_gravity= "center_vertical" android:layout_weight= "1"/></strong></p></p><p><p></p></p><p><p><strong><buttonandroid:id= "@+id/send" android:layout_width= "wrap_content" android:layout_height= "wrap_content" Android : layout_gravity= "center_vertical" android:text= "Send"/></strong></p></p><p><p><strong></LinearLayout></strong></p></p><p><p></p></p><p><p></p></p><p><p><strong></LinearLayout></strong></p></p><p><p>Here we have added two additional linearlayout, respectively, in the third and fourth row Positions. A EditText is placed in the third row to enter the Receiver's mobile phone number. A EditText and a Button are placed in line four to enter text messages and send text messages respectively.</p></p><p><p>Then modify the code in the mainactivity, add the processing logic to send the text message, the code is as Follows:</p></p><p><p></p></p><p><p><strong>public class Mainactivity extends Activity {</strong></p></p><p><p>......</p></p><p><p><strong>Private EditText to; Private edittextmsginput; Private Button send;</strong></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>Protected voidoncreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( r.layout.activity_main);</strong></p></p><p><p>......</p></p><p><p><strong>to = (EditText) Findviewbyid (r.id.to);</strong></p></p><p><p><strong>Msginput = (EditText) Findviewbyid (r.id.msg_input); Send = (Button) Findviewbyid (r.id.send); send.setonclicklistener (new onclicklistener () {</strong></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>public void OnClick (View V) {</strong></p></p><p><p><strong>Smsmanager Smsmanager = Smsmanager.getdefault ();</strong></p></p><p><p><strong>Smsmanager.sendtextmessage (to.gettext (). toString (), null,</strong></p></p><p><p></p></p><p><p></p></p><p align="right"><p align="right"><strong>}</strong></p></p><p align="right"><p align="right"><strong>});</strong></p></p><p align="right"><p align="right"><strong>}</strong></p></p><p align="right"><p align="right">......</p></p><p align="center"><p align="center"><strong>}</strong></p></p><br clear="all"><p><p><strong>m</strong> <strong>sginput.gettext (). toString ()</strong> <strong>, null, null);</strong></p></p><p><p></p></p><p><p>As you can see, we first obtained an instance of the new control in the layout file and then processed the specific logic of sending the text message in the Click event of the Send Button. When the Send button is clicked, smsmanager's Getdefault () method is called to get to the instance of smsmanager, and then the Sendtextmessage () method is called to send the Sms. The Sendtextmessage () method receives five parameters, where the first parameter is used to specify the Receiver's mobile phone number, The third parameter is used to specify the contents of the text message, the other parameters we do not use, the direct pass to Null.</p></p><p><p>As you may have guessed now, sending a text message also requires declaring permissions, so modify the code in Androidmanifest.xml as Follows:</p></p><p><p></p></p><p><p><strong><manifestxmlns:android= "http://schemas.android.com/apk/res/android"</strong> <strong>package= "com.example.smstest"</strong></p></p><p><p><strong>Android:versioncode= "1"</strong></p></p><p><p><strong>Android:versionname= "1.0" ></strong></p></p><p><p><strong><uses-permission android:name= "android.permission.RECEIVE_SMS"/></strong></p></p><p><p><strong><uses-permission android:name= "android.permission.SEND_SMS"/></strong></p></p><p><p>......</p></p><p><p><strong></manifest></strong></p></p><p><p>Now that the program is re-run, Smstest has the ability to send text Messages. however, Click the Send button although you can send a text message, but we do not know the success of the delivery is not, this time can use the Sendtextmessage () method of the fourth parameter to the text message sent status Monitoring. Modify the code in the mainactivity as Follows:</p></p><p><p></p></p><p><p><strong>public class Mainactivity extends Activity {</strong></p></p><p><p>......</p></p><p><p><strong>Private Intentfilter sendfilter;</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>Private Sendstatusreceiver sendstatusreceiver;</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>Protected voidoncreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( r.layout.activity_main);</strong></p></p><p><p></p></p><p><p></p></p><p><p></p></p><p><p>......</p></p><p><p><strong>Sendfilter = new Intentfilter (); sendfilter.addaction ("sent_sms_action"); Sendstatusreceiver = Newsendstatusreceiver (); Registerreceiver (sendstatusreceiver, sendfilter); send.setonclicklistener (new onclicklistener () {</strong></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>public void OnClick (View V) {</strong></p></p><p><p><strong>Smsmanager Smsmanager =smsmanager.getdefault (); Intent sentintent = newintent ("sent_sms_action"); Pendingintent Pi =pendingintent.getbroadcast</strong></p></p><p><p><strong>(mainactivity.this, 0, sentintent, 0);</strong></p></p><p><p><strong>Smsmanager.sendtextmessage (to.gettext (). tostring (), null, msginput.gettext (). tostring (), pi, null);</strong></p></p><p><p><strong>}</strong></p></p><p><p><strong>});</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>protected void OnDestroy () {super.ondestroy (); unregisterreceiver (messagereceiver);</strong></p></p><p><p><strong>Unregisterreceiver (sendstatusreceiver);</strong></p></p><p><p><strong>}</strong></p></p><p><p>......</p></p><p><p><strong>Class Sendstatusreceiver extends Broadcastreceiver {</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>public void OnReceive (context context, Intent Intent) {</strong></p></p><p><p><strong>If (getresultcode () = = Result_ok) {</strong></p></p><p><p><strong>//</strong> SMS sent successfully</p></p><p><p><strong>Toast.maketext (context, "Send succeeded", toast.length_long). show ();</strong></p></p><p><p><strong>} else {</strong></p></p><p><p><strong>//</strong> SMS send failed</p></p><p><p><strong>Toast.maketext (context, "Send failed", toast.length_long). show ();</strong></p></p><p><p><strong>}</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p></p></p><p><p></p></p><p><p><strong>}</strong></p></p><p><p><strong>}</strong></p></p><p><p>As you can see, in the click event of the Send button we call the Pendingintent Getbroadcast () method to get a Pendingintent object and pass it as the fourth argument to the Sendtextmessage () method. And then registered a new broadcast receiver sendstatusreceiver, This broadcast receiver is dedicated to listen to the status of text messages sent, when the value of Getresultcode () equals RESULT_OK will be prompted to send the success, otherwise the prompt send Failed.</p></p><p><p>Now rerun the program, enter the Receiver's mobile phone number and text message in the textbox, then click the Send button, as shown in result 8.8.</p></p><p><p></p></p><p align="center"><p align="center">Figure 8.8</p></p><p><p></p></p><p><p>Note that although the prompt to send a successful, but actually use the simulator to send text messages to the other side is impossible to receive, only the project to run on the phone, to really realize the function of sending text Messages.</p></p><p><p>In addition, according to international standards, the length of each text message must not exceed 160 characters, if you want to send more than this length of text messages, you need to split this message into multiple text messages to send, using Smsmanager sendmultipart-textmessage () method to achieve the above functions. Its usage and Sendtextmessage () method is basically similar, if you are interested, you can study it yourself, here will not start to Explain.</p></p><p><p>Android: Receive and send SMS</p></p></span>

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.