A detailed tutorial on sending and receiving SMS between simulators during Android development

Source: Internet
Author: User
Tags error code gettext xmlns port number

This article introduces how to achieve the function of SMS service (Sms,short message services) in Android by running two Android simulators. In this case, I would like to bring you more familiar with the concept and technical details of the Android application described earlier, and to dispatch interest through an example. The main reason I chose SMS as an example is that SMS is already very mature, with more information and technical details to explore, and I believe that most people send more text messages than they do on the phone.

1, restudying

Broadcast receiver: A broadcast receiver is such a component that it does nothing but accept the broadcast announcements and react accordingly. Many broadcasts originate from system code, such as announcing time zone changes, low battery power, taking pictures, and user changing language preferences. The application can also initiate a broadcast, for example, for other programs to know that some data has been downloaded to the device and that they can use the data

Broadcastreceiver class: Is the base class that accepts the intent (intents) sent by Sendbroadcast (). You can dynamically register instances of this class with Context.registerreceiver (), or statically publish them through Androidmanifest.xml <receiver> tags.

The broadcast recipient does not display a user interface. However, they start an activity to respond to the information they receive, or they may use Notificationmanager to notify the user. Notifications can be used in a variety of ways to get users ' attention-flashing backlight, vibrating devices, playing sounds, and so on. Typically placed in a persistent icon in the status bar, users can open access to information.




2, preparatory work: SMS related to the main categories of Smsmanager





Implementation SMS is mainly used in the Smsmanager class, which inherits from the Java.lang.Object class, and below we introduce the main members of the class.





Public method:





Arraylist&lt;string&gt; dividemessage (String text)


When a text message exceeds the maximum length of the SMS message, the SMS is divided into several pieces.


Parameter: text--initial message, cannot be empty


Return value: Ordered Arraylist&lt;string&gt;, can be combined back to the initial message


Static Smsmanager Getdefault ()


Gets the default instance of the Smsmanager.


Return value: default instance of Smsmanager


void Senddatamessage (String destinationaddress, String scaddress, short destinationport, byte[] data, pendingintent Sentintent, Pendingintent deliveryintent)


Sends an SMS based data to the specified application port.


Parameters:


1), the destination address of the destinationaddress--message


2), scaddress--Service center address or null use the current default SMSC 3) destinationport--The destination port number of the message


4, the body of the data--message, that is, the message to send the data


5), sentintent--if not NULL, when the message successfully sent or failed this pendingintent broadcast. The result code is ACTIVITY.RESULT_OK, or one of Result_error_generic_failure, Result_error_radio_off, RESULT_ERROR_NULL_PDU represents an error. The corresponding result_error_generic_failure,sentintent may include an additional "error code" containing a radio broadcast technology-specific value that is usually useful only when repairing a failure.


Each SMS-based application control detection sentintent. If the sentintent is empty, the caller will detect all unknown applications, which will cause a smaller number of SMS to be sent at the time of Detection.


6), deliveryintent--if not NULL, when the message successfully transmitted to the recipient of this pendingintent broadcast.


Exception: Throws IllegalArgumentException exception if destinationaddress or data is empty.


void Sendmultiparttextmessage (String destinationaddress, String scaddress, arraylist&lt;string&gt; parts, ArrayList &lt;PendingIntent&gt; sentintents, arraylist&lt;pendingintent&gt; deliverintents)


Sends a partial text based on SMS, which has been split into the correct size by calling Dividemessage (String text).


Parameters:


1), the destination address of the destinationaddress--message


2), scaddress--Service center address or null use the current default SMSC


3), parts--ordered Arraylist&lt;string&gt, can be combined into the initial message


4), sentintents--and Senddatamessage method, but here is a group of pendingintent


5), deliverintents--and Senddatamessage method, but here is a group of pendingintent


Exception: Throws IllegalArgumentException exception if destinationaddress or data is empty.


void Sendtextmessage (String destinationaddress, String scaddress, string text, Pendingintent sentintent, pendingintent Deliveryintent)


Sends an SMS based text. The meaning of the parameter is no longer described as the existing one before the exception.





Constant:





public static final int result_error_generic_failure


Indicates a normal error with a value of 1 (0x00000001)


public static final int Result_error_no_service


Indicates that the service is currently unavailable with a value of 4 (0x00000004)


public static final int RESULT_ERROR_NULL_PDU


Indicates no PDU provided, value 3 (0x00000003)


public static final int Result_error_radio_off


Indicates that the wireless broadcast was explicitly closed with a value of 2 (0x00000002)


public static final int Status_on_icc_free


Represents free space with a value of 0 (0x00000000)


public static final int Status_on_icc_read


Indicates receive and read, value 1 (0x00000001)


public static final int status_on_icc_sent


Represents a store and has been sent with a value of 5 (0x00000005)


public static final int Status_on_icc_unread


Indicates a receive but unread value of 3 (0x00000003)


public static final int status_on_icc_unsent


Represents a store but is sent with a value of 7 (0x00000007)





3, simple SMS send the program





1, first, edit the layout file Res/layout/main.xml, to achieve the results we want, the interface is as follows:





Figure 1, program running interface





The corresponding XML code is as follows:





&lt;?xml version= "1.0" encoding= "Utf-8"?&gt;


&lt;linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"


android:orientation= "Vertical"


Android:layout_width= "Fill_parent"


android:layout_height= "Fill_parent" &gt;


&lt;textview android:layout_width= "Fill_parent"


android:layout_height= "Wrap_content"


android:text= "@string/txtphoneno"/&gt;





&lt;!--text ' s value define in Res/values/strings.xml--&gt;





&lt;edittext android:layout_width= "Fill_parent"


android:layout_height= "Wrap_content"


Android:id= "@+id/edtphoneno"/&gt;





&lt;textview android:layout_width= "Fill_parent"


android:layout_height= "Wrap_content"


android:text= "@string/txtcontent"/&gt;





&lt;edittext android:layout_width= "Fill_parent"


android:layout_height= "Wrap_content"


Android:minlines= "3"


Android:id= "@+id/edtcontent"/&gt;





&lt;button android:layout_width= "Wrap_content"


android:layout_height= "Wrap_content"


android:text= "@string/btntext"


Android:id= "@+id/btnsend"/&gt;


&lt;/LinearLayout&gt;





The corresponding value to add the text of the view defined above in Res/values/strings.xm, as follows:





&lt;?xml version= "1.0" encoding= "Utf-8"?&gt;


&lt;resources&gt;


&lt;string name= "Txtphoneno" &gt;please input phone no:&lt;/string&gt;


&lt;string name= "txtcontent" &gt;please input sms\ ' s content:&lt;/string&gt;


&lt;string name= "Btntext" &gt;send!&lt;/string&gt;


&lt;string name= "App_name" &gt;SMS&lt;/string&gt;


&lt;/resources&gt;





2, after these preparations, I want to start writing code to achieve a simple text message sent.





After we have built the interface in the first step, we now need to write the business logic on the basis of the above. The approximate process is: In the Java source file, get the phone number the user entered in the Edtphoneno, enter the content to be sent in Edtcontent, and then click the Btnsend button to send a text message, To achieve this, we need to set up btnsend Onclicklistener to achieve the function of triggering a message when clicked, and to send a text message to use the method interface provided by the Smsmanager class we described earlier.





The code for setting the Btnsend Onclicklistener is as follows:





Btnsend.setonclicklistener (New View.onclicklistener () {


public void OnClick (View v) {


String Phoneno = Edtphoneno.gettext (). toString ();


String message = Edtcontent.gettext (). toString ();


if (phoneno.length () &gt; 0 &amp;&amp; message.length () &gt; 0) {


Call sendsms to send message to Phoneno


Sendsms (Phoneno, message);


}


Else


Toast.maketext (Getbasecontext (),


"Please enter both phone number and message."


Toast.length_short). Show ();


}


});





The code for sending SMS functions is as follows:





private void Sendsms (string phonenumber, String message) {


---Sends an SMS to another device---


Smsmanager SMS = Smsmanager.getdefault ();


pendingintent pi = pendingintent.getactivity (this, 0,





New Intent (This,textmessage.class), 0);


If message ' s length than 70,


Then call Dividemessage to dive message into several part





and call Sendtextmessage ()


Else direct call Sendtextmessage ()


if (Message.length () &gt; 70) {


Arraylist&lt;string&gt; msgs = sms.dividemessage (message);


for (String msg:msgs) {


Sms.sendtextmessage (PhoneNumber, NULL, MSG, PI, null);


}


} else {


Sms.sendtextmessage (PhoneNumber, NULL, message, PI, null);


}


Toast.maketext (textmessage.this, "SMS Send Complete", Toast.length_long). Show ();


}








If you have read the introduction of the Smsmanager class introduced in section 2nd, the code should be well understood. To illustrate here, the Sendtextmessage method of the 4th and 5th parameters pendingintent set to NULL, so that the message can not be based on the state after the text of the corresponding things, such as the message sent after the failure of the reminder, the recipient received a successful receipt ... The complete process source code is as follows:





Package skynet.com.cnblogs.www;





Import java.util.ArrayList;





Import android.app.Activity;


Import android.app.PendingIntent;


Import android.content.Intent;


Import Android.os.Bundle;


Import Android.telephony.SmsManager;


Import Android.view.View;


Import android.widget.*;





public class TextMessage extends activity {


/** called the activity is a. */


@Override


public void OnCreate (Bundle savedinstancestate) {


Super.oncreate (savedinstancestate);





Setcontentview (R.layout.main);


Btnsend = (Button) Findviewbyid (r.id.btnsend);


Edtphoneno = (edittext) Findviewbyid (R.id.edtphoneno);


Edtcontent = (edittext) Findviewbyid (r.id.edtcontent);





Btnsend.setonclicklistener (New View.onclicklistener () {


public void OnClick (View v) {


String Phoneno = Edtphoneno.gettext (). toString ();


String message = Edtcontent.gettext (). toString ();


if (phoneno.length () &gt; 0 &amp;&amp; message.length () &gt; 0) {


Call sendsms to send message to Phoneno


Sendsms (Phoneno, message);


} else


Toast.maketext (Getbasecontext (),


"Please enter both phone number and message."


Toast.length_short). Show ();


}


});


}





Private Button btnsend;


Private EditText Edtphoneno;


Private EditText edtcontent;





private void Sendsms (string phonenumber, String message) {


---Sends an SMS to another device---


Smsmanager SMS = Smsmanager.getdefault ();


pendingintent pi = pendingintent.getactivity (this, 0, new Intent) (This,


Textmessage.class), 0);


If message ' s length than 70,


Then call Dividemessage to dive message into several part, and call


Sendtextmessage ()


Else direct call Sendtextmessage ()


if (Message.length () &gt; 70) {


Arraylist&lt;string&gt; msgs = sms.dividemessage (message);


for (String msg:msgs) {


Sms.sendtextmessage (PhoneNumber, NULL, MSG, PI, null);


}


} else {


Sms.sendtextmessage (PhoneNumber, NULL, message, PI, null);


}


Toast.maketext (textmessage.this, "SMS Send Complete", Toast.length_long). Show ();


}


}





3 before running, add the permission to send text messages in the manifest file Androidmanifest.xml:





&lt;?xml version= "1.0" encoding= "Utf-8"?&gt;


&lt;manifest xmlns:android= "Http://schemas.android.com/apk/res/android"


Package= "Skynet.com.cnblogs.www"


Android:versioncode= "1"


Android:versionname= "1.0" &gt;


&lt;application android:icon= "@drawable/icon" android:label= "@string/app_name" &gt;


&lt;activity android:name= ". TextMessage "


Android:label= "@string/app_name" &gt;


&lt;intent-filter&gt;


&lt;action android:name= "Android.intent.action.MAIN"/&gt;


&lt;category android:name= "Android.intent.category.LAUNCHER"/&gt;


&lt;/intent-filter&gt;


&lt;/activity&gt;





&lt;/application&gt;


&lt;uses-permission android:name= "Android.permission.SEND_SMS"/&gt;


&lt;/manifest&gt;





3.1, run the SMS program to another Android simulator text message





Run the TextMessage program we wrote above, and then switch to the Tools directory under Windows command line, and enter emulator data Smsreceiver as follows:





This will start an Android emulator, as follows: (Note that its number: 5556, is to use this number to communicate with it)

Figure 2, starting an Android emulator via emulator

By using our TextMessage program to launch the Android Simulator, write a text message:

Figure 3, textmessage program 5556 Simulator text message

After clicking Send, the No. 5556 Android Simulator, launched via the command line, will receive the SMS we just sent, as follows:

Figure 4, tips for receiving text messages




Tips:





If you start the Android emulator prompt with the emulator command line, "NO DNS servers found! ", when we send the SMS simulator is not received."





In Windows, if the computer does not intervene in the network, that is, the failure to find a DNS server this situation!


Under the Mac, if prompted for this warning, this can be done: check if you have/etc/resolv.conf files, and if not, pass the following command line





Ln-s/private/var/run/resolv.conf/etc/resolv.conf can be solved.





4, SMS Enhancement (i)





Above we have implemented a simple SMS program, we have to enhance it below! You must have noticed that the 4th and 5th parameters in the Sendtextmessage method of the SMS program above are set to null pendingintent, that is, Sentintent and deliveryintent.





The 4th parameter,-sendintent, is triggered when a message is sent successfully or sent unsuccessfully. The result code of the broadcast receiver, ACTIVITY.RESULT_OK indicates success, or Result_error_generic_failure, Result_error_radio_off, Result_error_null_ One of the PDUs indicates an error. The corresponding result_error_generic_failure,sentintent may include an additional "error code" containing a radio broadcast technology-specific value that is usually useful only when repairing a failure. The 5th parameter,-deliveryintent, is triggered only if the target receives your SMS message.





In order to track the status of the sent messages, implement and register broadcast Receiver (broadcast receivers) to listen for parameters passed to the Sendtextmessage method pending Intents. Below we will implement and register this broadcast receiver:





String sent_sms_action= "Sent_sms_action";


String delivered_sms_action= "Delivered_sms_action";





Create the Sentintent parameter


Intent sentintent=new Intent (sent_sms_action);


Pendingintent Sentpi=pendingintent.getbroadcast (


This


0,


Sentintent,


0);





Create the Deilverintent parameter


Intent deliverintent=new Intent (delivered_sms_action);


Pendingintent Deliverpi=pendingintent.getbroadcast (


This


0,


Deliverintent,


0);





Register the broadcast receivers


Registerreceiver (New Broadcastreceiver () {


@Override


public void OnReceive (context _context,intent _intent)


{


Switch (Getresultcode ()) {


Case ACTIVITY.RESULT_OK:


Toast.maketext (Getbasecontext (),


"SMS sent success Actions",


Toast.length_short). Show ();


Break


Case Smsmanager.result_error_generic_failure:


Toast.maketext (Getbasecontext (),


"SMS Generic failure Actions",


Toast.length_short). Show ();


Break


Case Smsmanager.result_error_radio_off:


Toast.maketext (Getbasecontext (),


"SMS Radio Off failure Actions",


Toast.length_short). Show ();


Break


Case SMSMANAGER.RESULT_ERROR_NULL_PDU:


Toast.maketext (Getbasecontext (),


"SMS null PDU failure Actions",


Toast.length_short). Show ();


Break


}


}


},


New Intentfilter (sent_sms_action));


Registerreceiver (New Broadcastreceiver () {


@Override


public void OnReceive (context _context,intent _intent)


{


Toast.maketext (Getbasecontext (),


"SMS delivered Actions",


Toast.length_short). Show ();


}


},


New Intentfilter (delivered_sms_action));











In the basic completion of the work to do, the next thing to do is to change the sendtextmessage 4th and 5th parameters to SENTPI, Deliverpi, this work is basically completed, the modified Sendsms method is as follows:





private void Sendsms (string phonenumber, String message) {


---Sends an SMS to another device---


Smsmanager SMS = Smsmanager.getdefault ();


String sent_sms_action = "Sent_sms_action";


String delivered_sms_action = "Delivered_sms_action";





Create the Sentintent parameter


Intent sentintent = new Intent (sent_sms_action);


Pendingintent SENTPI = pendingintent.getbroadcast (this, 0, sentintent,


0);





Create the Deilverintent parameter


Intent deliverintent = new Intent (delivered_sms_action);


Pendingintent Deliverpi = pendingintent.getbroadcast (this, 0,


Deliverintent, 0);





Register the broadcast receivers


Registerreceiver (New Broadcastreceiver () {


@Override


public void OnReceive (context _context, Intent _intent) {


Switch (Getresultcode ()) {


Case ACTIVITY.RESULT_OK:


Toast.maketext (Getbasecontext (),


"SMS sent success Actions", Toast.length_short)


. Show ();


Break


Case Smsmanager.result_error_generic_failure:


Toast.maketext (Getbasecontext (),


"SMS Generic failure Actions", Toast.length_short)


. Show ();


Break


Case Smsmanager.result_error_radio_off:


Toast


. Maketext (Getbasecontext (),


"SMS Radio Off failure Actions",


Toast.length_short). Show ();


Break


Case SMSMANAGER.RESULT_ERROR_NULL_PDU:


Toast.maketext (Getbasecontext (),


"SMS null PDU failure Actions", Toast.length_short)


. Show ();


Break


}


}


}, New Intentfilter (sent_sms_action));


Registerreceiver (New Broadcastreceiver () {


@Override


public void OnReceive (context _context, Intent _intent) {


Toast.maketext (Getbasecontext (), "SMS delivered actions",


Toast.length_short). Show ();


}


}, New Intentfilter (delivered_sms_action));





If message ' s length than 70,


Then call Dividemessage to dive message into several part, and call


Sendtextmessage ()


Else direct call Sendtextmessage ()


if (Message.length () &gt; 70) {


Arraylist&lt;string&gt; msgs = sms.dividemessage (message);


for (String msg:msgs) {


Sms.sendtextmessage (PhoneNumber, NULL, MSG, SENTPI, Deliverpi);


}


} else {


Sms.sendtextmessage (PhoneNumber, NULL, message, SENTPI, DELIVERPI);


}


}





After the operation, send the text message successfully, you can see the following interface:





Figure 5, enhanced SMS (i)





5, SMS Enhancements (ii)





The next enhancement is to enable SMS to send binary data. To send data to use the Senddatamessage method of the Smsmanager class, similar to the Sendtextmessage method, except that the method has one more parameter for the target port, the process of building the SMS is not described here.





6. The intent of restudying





This series is briefly preceded by the intention (Intent), here again briefly, in the SMS receiving program and using Intent to send SMS we need to use. The three major components of the Android application,--activities, Services, and broadcast Receiver, are triggered by a message called intent (Intent). Below take acitvity as an example, introduce intent. Android uses this particular class of intent to switch between activity and activity. The intent class is used to describe the functionality of the application. In the description structure of intent, there are two most important parts: the corresponding data of action and action. Typical action type has main, VIEW, PICK, Edit and so on, we use in the message receiving program to extract the action type from the broadcast intention and to judge whether is "Android.provider.Telephony.SMS_RECEIVED", And then take a deep step to deal with. The data corresponding to the action is expressed in the form of a URI. For example, to see how a person is contacted, you need to create a intent that moves to view, and a URI that represents the person.





It's easy to navigate from one screen to another by parsing various intent. When navigating forward, the activity will invoke the StartActivity ("Specify a Intent") method. The system then looks in the Intentfilter defined in all installed applications to find the most matching intent corresponding activity. The new activity begins to run after it receives a notification of the specified intent. When the StartActivity () method is invoked, the action that resolves the specified intent is triggered, which provides two key benefits:





The activity can reuse requests from other components in intent form.


Activity can be replaced at any time by a new activity with the same intentfilter.





7, preparation work: Smsmessage class





As the name suggests, the Smsmessage class is a message class, in order to better understand the Android SMS mechanism and better to write SMS related programs, here is a description of the class of public methods and constants, and nested enumerations, class members.





Public Method:





public static int[] Calculatelength (Charsequence msgbody, Boolean use7bitonly)


Parameters:


msgbody-the message to be encapsulated, use7bitonly-if true, a partial character that is not broadcast-specific 7-bit encoded is considered to be a single null character, and if False, and Msgbody contains a non-7-bit encoded character, the length calculation uses 16-bit encoding.


return value:


Returns an int array of 4 elements, int[0] indicates the number of SMS required to use, Int[1] represents the quantity used by the encoding unit, INT[2] represents the number of encoded units remaining to the next message, and int[3 the indicator that represents the size of the encoded unit.


public static int[] Calculatelength (String messagebody, Boolean use7bitonly)


Parameters and return values are similar to the above


public static Smsmessage CREATEFROMPDU (byte[] PDU)


Create a smsmessage from the original PDU (protocol description units). This method is important when we are writing a SMS receiver that uses the bytes it obtains from the broadcast intent we receive to create Smsmessage.


Public String Getdisplaymessagebody ()


Returns the subject of the SMS message, or the email message body (if the message comes from an email gateway). Returns NULL if the message body is not available. This method is also very important, when we write the message receiving program also need to use.


Public String getdisplayoriginatingaddress ()


Return the information source address, or email address (if the message comes from an email gateway). Returns NULL if the message body is not available. This method is often used in caller ID, SMS receiver programs.


Public String Getemailbody ()


If Isemail is true, that is, a message that returns the address sent via the gateway, or null.


public int GETINDEXONICC ()


Returns the index of the message recorded on ICC (starting from 1)


Public String Getmessagebody ()


Returns the body of the message as a string if it exists and is text-based.


Public Smsmessage.messageclass Getmessageclass ()


Returns the class of the message.


Public String getoriginatingaddress ()


Returns the caller address of the SMS information as string, or null if unavailable.


Public byte[] GETPDU ()


Returns the raw PDU data for the message.


public int Getprotocolidentifier ()


Gets the protocol identifier.


Public String Getpseudosubject ()


Public String getservicecenteraddress ()


Returns the address of the broadcast Message SMS Service center, if none is null.


public int GetStatus ()


GSM: For a sms-status-report message, it returns the Status field for the state report. This field represents the status of the previously submitted SMS message.


CDMA: To not affect the status code from GSM, the value is moved to 31-16 bits. This value consists of an error class (25-16 bits) and a status code (23-16 bits).


If 0, the message that was sent before is received.


public int GETSTATUSONICC ()


Returns the status of the message on ICC (read, unread, sent, not sent). There are several values below: Smsmanager.status_on_icc_free, Smsmanager.status_on_icc_read, Smsmanager.status_on_icc_unread, Smsmanager.status_on_icc_send, smsmanager.status_on_icc_unsent These values in the previous chapter of the Smsmanager class introduction has mentioned.


public static SMSMESSAGE.SUBMITPDU GETSUBMITPDU (


String scaddress, String destinationaddress,


Short Destinationport, byte[] data,


Boolean statusreportrequested)


Parameters: Scaddress-The address of the service center (Sercvice Centre addresses, NULL is the default), Destinationaddress-the destination address of the message, destinationport-the port number to send the message to the destination , data-message information.


Return value: A SUBMITPDU that contains the encoded SC address (if specified) and the message content, or null if the encoding is incorrect.


public static SMSMESSAGE.SUBMITPDU GETSUBMITPDU (


String scaddress, String destinationaddress,


String message, Boolean statusreportrequested)


Similar to the above.


public static int Gettplayerlengthforpdu (String PDU)


Returns the tp-layer-length of the specified sms-submit PDU, in bytes rather than 16 characters.


Public long Gettimestampmillis ()


Returns the service center timestamp in Currenttimemillis () format.


Public byte[] Getuserdata ()


Returns user data minus user data head (if any)


public boolean iscphsmwimessage ()


Judge whether it is cphs MWI message


public boolean isemail ()


If the message is from an email gateway and the email sender (sender), subject (subject), resolver (parsed body) is available, return true.


public boolean ismwiclearmessage ()


Determines whether a message is a cphs voice message or message waiting for a MWI purge (clear) message.


public boolean ismwisetmessage ()


Determines whether a message is a cphs voice message or message waiting for a MWI setting (set) message.


public boolean Ismwidontstore ()


Returns true if the message is a "waiting indication Group:discard messages" notification and should not be saved, otherwise returns false.


public boolean isreplace ()


Determine if it is a "replace short message" SMS


public boolean isreplypathpresent ()


Determines whether the Tp-reply-path bit of the message is set in the message.


public boolean isstatusreportmessage ()


Determine if it is a sms-status-report message.





constant Value:





public static final int encoding_16bit: value 3 (0x00000003)


public static final int encoding_8bit: value 2 (0x00000002)


public static final int Encoding_unknown: A value of 0 (0x00000000), the size of the user data Encoding unit.


public static final int max_user_data_bytes: The value is 140 (0x0000008c), which represents the maximum number of load bytes per message.


public static final int max_user_data_bytes_with_header:134 (0x00000086), if a user data has a header, the value represents its maximum number of load bytes, This value assumes that the header contains only concatenated_8_bit_refenence elements.


The public static final int max_user_data_septets: The value is 160 (0X000000A0), which represents the maximum number of load septets per message.


public static final int Max_user_data_septets_with_header: value is 153 (0x00000099), if there is a user data header, The value represents the maximum number of load septets This value assumes that the header contains only concatenated_8_bit_refenence elements.





Enumeration values for nested enumeration member Smsmessage.messageclass:





public static final Smsmessage.messageclass Class_0


public static final Smsmessage.messageclass Class_1


public static final Smsmessage.messageclass class_2


public static final Smsmessage.messageclass Class_3


public static final Smsmessage.messageclass Class_unknown





The public method of nesting enumeration member Smsmessage.messageclass:





public static Smsmessage.messageclass valueof (string name): Returns the value of a string of values


public static final messageclass[] VALUES (): Returns an array of value for MessageClass





fields for nested class members SMSMESSAGE.SUBMITPDU:





Public byte[] Encodedmessage: Encoded message


Public byte[] encodedscaddress: Encoded Service Center Address





Public method for nested class member SMSMESSAGE.SUBMITPDU:





Public String toString ()


Returns a description string that contains a simple, readable object. Subclasses are encouraged to override this method and provide the type and data to implement the object. The default implementation simply connects the class name, @, and hexadecimal-represented object hash code, that is, the following form: GetClass (). GetName () + ' @ ' + integer.tohexstring (hashcode ())





8. SMS Receiving Program





When an SMS message is received, a new broadcast intent is triggered by the Android.provider.Telepony.SMS_RECEIVED action. Note: This is a string literal (string literal), but the SDK does not currently include a reference to this string, so you must specify it yourself when you want to use it in your application. Now we're going to start building an SMS Receive program:





1, similar to the SMS transmitter, to specify permissions in the manifest file Androidmanifest.xml to allow receiving sms:&lt;uses-permission android:name= " Android.permission.RECEIVER_SMS "/&gt;





To be able to send text back, you should also add the permission to send.





2. The application listens for SMS intent broadcasts, and the SMS broadcast intent contains the incoming SMS details. We want to extract the Smsmessage object from it so that we use the PDU key to extract an SMS PDUs Array (protocol description units-encapsulates an SMS message and its metadata), and each element represents an SMS message. To convert each PDU byte array to an SMS message object, you need to invoke SMSMESSAGE.CREATEFROMPDU.





Each smsmessage contains details of the SMS message, including the start address (phone number), the timestamp, the message body. Write a class Smsreceiver code to receive SMS below:





Package skynet.com.conblogs.www;





Import Android.content.BroadcastReceiver;


Import Android.content.Context;


Import android.content.Intent;


Import Android.os.Bundle;


Import Android.telephony.SmsManager;


Import Android.telephony.SmsMessage;


Import Android.widget.Toast;





public class Smsreceiver extends Broadcastreceiver {


@Override


public void OnReceive (context _context, Intent _intent) {


if (_intent.getaction (). Equals (Sms_receiver)) {


Smsmanager SMS = Smsmanager.getdefault ();





Bundle Bundle = _intent.getextras ();


if (bundle!= null) {


Object[] PDUs = (object[]) bundle.get ("PDUs");


smsmessage[] messages = new Smsmessage[pdus.length];


for (int i = 0; i &lt; pdus.length; i++)


Messages[i] = SMSMESSAGE.CREATEFROMPDU ((byte[)) pdus[i]);


for (Smsmessage message:messages) {


String msg = Message.getmessagebody ();


String to = message.getoriginatingaddress ();


if (Msg.tolowercase (). StartsWith (querystring)) {


String out = msg.substring (Querystring.length ());


Sms.sendtextmessage (To, NULL, out, NULL, NULL);





Toast.maketext (_context, "success"),


Toast.length_long). Show ();


}


}


}


}


}





private static final String querystring= "@echo";


private static final String sms_receiver=


"Android.provider.Telephony.SMS_RECEIVED";


}





The function of the above code is to extract the caller ID, SMS content from the broadcast intention received, and then send the text message plus @echo head back to the caller number, and display a toast message on the screen for success.





9, another way to send text messages: The use of intent





In the previous article we used the Smsmanager class to implement the function of sending SMS, and did not use the built-in client. In fact, we rarely do this by ourselves in the application to fully implement a complete SMS client. Instead, we will use it to pass the content and destination mobile number to the built-in SMS client and send it.





Below I'll show you how to use the intent implementation to send us SMS with our things to the built-in SMS client. In order to achieve this function, it is necessary to use the StartActivity ("Specify a Intent") method, and specify intent action for Intent.action_sendto, with SMS: Specify the target mobile phone number, use Sms_body to specify the information content. The Java source file looks like this:





Package skynet.com.cnblogs.www;





Import android.app.Activity;


Import android.content.Intent;


Import Android.net.Uri;


Import Android.os.Bundle;


Import Android.view.View;


Import Android.widget.Button;


Import Android.widget.EditText;


Import Android.widget.Toast;








public class TextMessage extends activity {


/** called the activity is a. */


@Override


public void OnCreate (Bundle savedinstancestate) {


Super.oncreate (savedinstancestate);





Setcontentview (R.layout.main);


Btnsend = (Button) Findviewbyid (r.id.btnsend);


Edtphoneno = (edittext) Findviewbyid (R.id.edtphoneno);


Edtcontent = (edittext) Findviewbyid (r.id.edtcontent);





Btnsend.setonclicklistener (New View.onclicklistener () {


public void OnClick (View v) {


String Phoneno = Edtphoneno.gettext (). toString ();


String message = Edtcontent.gettext (). toString ();


if (phoneno.length () &gt; 0 &amp;&amp; message.length () &gt; 0) {


Intent smsintent=new Intent (Intent.action_sendto,


Uri.parse ("SMS:" +edtphoneno.gettext (). toString ()));


Smsintent.putextra ("Sms_body", Edtcontent.gettext (). toString ());


TextMessage.this.startActivity (smsintent);


} else


Toast.maketext (Getbasecontext (),


"Please enter both phone number and message."


Toast.length_short). Show ();


}


});


}





Private Button btnsend;


Private EditText Edtphoneno;


Private EditText edtcontent;


}





Note the red bold part of the code, which is the core code to implement this feature! Layout file Maim.xml and value file String.xml as in the previous article, this is no longer described here. The results of the operation are shown below:





Figure 2, program main interface

After clicking the Send button, go to the built-in SMS client and pass the values we entered, as shown in the following figure:

Figure 3, the content is passed to the built-in SMS client

After sending, the No. 5556 Android Simulator will receive the message we sent, as shown in the following figure:

Figure 5, after sending No. 5556, the Android simulator received the message


10, enhanced SMS to MMS

We've talked so much, we've just implemented a simple SMS feature, what if we want to send pictures and audio (⊙o⊙)? No hurry, now let's change the SMS Send program described in section 9th to MMS.

We can attach a file to our message to send as an attachment, call the Putextra () method with the URI of the Intent.extra_stream and attachment resource, and attach to the information. and set the intent type to Mime-type. Note that the built-in MMS does not include a action_sendto action intent receiver, we need to use the type of action is Action_send, and the target cell phone number is not in the use of SMS: But address. The main code is as follows:

//Get the URI of a piece of media to attach.
Uri Attached_uri = Uri.parse ("CONTENT://MEDIA/EXTERNAL/IMAGES/MEDIA/1");
//Create A new MMS intent
Intent mmsintent = new Intent (intent.action_send, Attached_uri);
Mmsintent.putextra ("Sms_body", Edtcontent.gettext (). toString ());
Mmsintent.putextra ("Address", Edtphoneno.gettext (). toString ());
Mmsintent.putextra (Intent.extra_stream, Attached_uri);
Mmsintent.settype ("Image/png");
StartActivity (mmsintent);

 

Replaces this code with the red Bold code in section 9th and completes the construction of an MMS.

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.