You can send scheduled text messages on Android

Source: Internet
Author: User
ArticleDirectory
    • Extended learning

The interface for scheduled text messages is relatively simple. It only contains several edittext and buttons. The functions include adding contacts, writing text messages, setting time, and saving and sending messages. Android has four components: Activity, intent, broadcast, and service. As long as you have mastered these four components, Android development becomes very simple. In this project, I used the first three services. Activity can be understood as a window or container, which is visualized and can carry various controls. Intent and broadcast will be described later.

The time setting is implemented through the Android. App. timepickerdialog class. This class provides a visual window, which is user-friendly for users.

There are three ways to store data in Android. All data in Android is private, but differentProgramData can still be transmitted to each other, so how does Android achieve this? Originally, there was a contentprovide in Android. contentprovide is used to encapsulate data. External programs can access data through the contentprovide interface. Android uses SQLite, a lightweight embedded database. This database has very low hardware requirements and occupies a small amount of memory, but it is very fast and widely used in embedded devices. However, because the scheduled text message only needs to be stored in the contact's phone number and text message, I chose another storage method, sharedpreferences. Sharedpreferences provides a simple key-Value Pair storage method. It is generally used to store some simple and small amount of data. It is no longer appropriate to store a text message.

The problem that must be solved when the software is closed after the time is set,When the time arrives, the software can restart sending text messages. This feature is implemented by the alarm wake-up function in Android.. In the Android. App. alarmmanager class, a mechanism is provided to allow the program to access the system's alarm service, so that the application can be set to execute at a certain time point in the future. When that time point is reached, the system will broadcast an intent to start the program that registers the alarm service. Intent is defined in the official document as follows: an intent is an abstract description of an operation to be executed med. Intent is an abstract description of the action to be executed. Here, I mainly send intent to broadcast, and then create a new broadcastreceiver to receive the message. When the time arrives, a new activity is enabled to send the text message.

You need to create an activity to send text messages. In this activity, you only need to use the smsmanager class. This class provides the method to send text messages. After a text message is sent, remember to turn off the activity that sent the text message. Because the life cycle of the activity is 0, there is no need to exist after the text message is sent. Use finish () method.

This is the main idea of the software implementation, but there are still many problems after this rough completion. For example, if the set time has passed, after you click Save and send, the message will be sent immediately. The edited text message cannot be viewed or edited before being sent. You can only manually enter the number in the send number column, but cannot import the message from the address book...

As a result, I spent my main energy on software improvement. The problem of time setting is easy to solve. You only need to judge the rationality of the time when you click the Save button of the text message. However, you cannot obtain the set time by clicking the save text message button. Therefore, you must click the set time button to determine the time, then, a variable is changed based on the rationality of the time. In the method of saving the text message, the variable is judged to see if the time setting meets the requirements. Note that the system time is still obtained using the Java syntax, that is, final calendar CA = calendar. getinstance (); int hours = Ca. get (calendar. hour); int minutes = Ca. get (calendar. minute); so there is a small problem. As we all know, the system time obtained by the Java language is in the 12-hour format. That is to say, if the system time is, it is obviously not allowed for users to set, because scheduled text messages can only be sent within one day, 8: 00 indicates that eight o'clock in the morning has passed. However, the number of hours obtained by the system is 2, because the system time is in the 12-hour format. By comparing 8 to 2, the time setting seems to be okay, but in fact the time setting is incorrect. Therefore, the Ca. Get (calendar. am_pm) value should be determined to determine whether it is morning or afternoon. If it is afternoon, 12 hours should be added.

Compared with the time issue, saving the text message is very simple. You only need to sharedpreferences in the main activity once, and then the value will be blank after the text message is sent successfully.

during the entire software production process, the biggest problem I encountered was the import of contacts. As I mentioned earlier, the android SDK is updated quickly and greatly, which is particularly evident in the address book! Because I am using the latest Android SDK 2.2, all the information about reading contacts in the address book is written using the API of Android SDK 1.5, when I use the android SDK 2.2 API in Android SDK 1.5, eclipse will warn that it is not recommended. No way. I can only re-learn the related APIs in Android SDK 2.2. The APIs of the two have changed, and many problems also occur when they are subsequently adapted to listview. When reading a contact, the cursor is obtained. Then, the query () method is used to read the cursor according to the URI, that is, cursor c = getcontentresolver (). query (phones. content_uri, null, null); the difference is that in Android SDK 2.2, phones. content_uri is changed to contactscontract. contacts. content_uri. The name and phone number of the contact to be read are also different. No wonder some people say that it is very painful to develop Android, because the compatibility between different versions should be considered. There is no way to do this. The Android system is a new system after all, and it cannot be compared with Symbian and WM in terms of maturity. However, it seems that the android update speed has been lowered, and there should be no significant API changes in the future. Developers should be relieved! After that, it is adapted to the listview, displaying the contact information in the listview, and uploading the stored contact phone number to the main activity in the listview clicking method. The data must be transmitted to intent, but different from the previous simple jump, this jump requires data to be obtained, and startactivity () is changed to startactivityforresult ().

In this way, the entire program is relatively complete. Of course, this small software still has many problems, suchCannot send text messages across daysAnd the interface is not very friendly. To solve these problems, I need to constantly study and try. Through this small program, I realized that my android development journey was just getting started. However, I also found that Android phones not only attract users, because we all say that Android phones are the best choice for players, but also a great experience in development, it provides a set of excellent and powerful development tools. With the strong eclipse and Java language in the Open Source world, we have reason to believe that this little green man will fly more and more farther and farther...

 

In addition to creating two edittext controls and one button control in oncreat (), the main program sets onclicklinstener () for users to clear the content when they click the edittext control, send a text message when you click the button, and check the regular expression of the recipient's phone number through the custom methods isphonenumbervalid () and iswithin70, and whether the text message contains more than 70 characters.

The pendingintent. getbroadcast () method to customize pendingintent and perform broadcasting, and then use smsmanager. getdefault () (when processing SMS-related activities, such as sending data, text, and pdu sms information, this static method must be called) the pre-built smsmanager uses sendtextmessage () to complete the task of sending text messages.

 

  1. /* Check whether the string is a telephone number and return the true or false value */
  2. Public static Boolean isphonenumbervalid (string phonenumber)
  3. {
  4. Boolean isvalid = false;
  5. /* Acceptable telephone formats include:
  6.  
  7. * ^ //(? : You can start "("
  8.  
  9. * (// D {3}): followed by three digits
  10.  
  11. *//)? : You can use ")" to continue
  12.  
  13. * [-]? : After the preceding format, you can use "-".
  14.  
  15. * (// D {3}): followed by three digits
  16.  
  17. * [-]? : Select "-" to continue.
  18.  
  19. * (// D {5}) $: end with five digits.
  20.  
  21. * The following numeric formats can be compared:
  22.  
  23. * (123) 456-7890,123-456-7890,123 4567890, (123)-456-7890
  24.  
  25. */
  26. String expression =
  27. "^ //(? (// D {3 })//)? [-]? (// D {3}) [-]? (// D {5}) $ ";
  28. Charsequence inputstr = phonenumber;
  29. /* Create pattern */
  30. Pattern pattern = pattern. Compile (expression );
  31. /* Pass pattern as a parameter to matcher for regular expression */
  32. Matcher = pattern. matcher (inputstr );
  33. /* Create pattern2 */
  34. Pattern pattern2 = pattern. Compile (expression2 );
  35. /* Pass pattern2 to matcher2 as the regular expression */
  36. Matcher matcher2 = pattern2.matcher (inputstr );
  37. If (matcher. Matches () | matcher2.matches ())
  38. {
  39. Isvalid = true;
  40. }
  41. Return isvalid;
  42. }
  43. Public static Boolean iswithin70 (string text)
  44. {
  45. If (text. Length () <= 70)
  46. {
  47. Return true;
  48. }
  49. Else
  50. {
  51. Return false;
  52. }
  53. }
  54. }
Androidmanifest. xml

Note that you need to add the permission Android. Permission. send_sms to send text messages.

Extended learning

// Obtain the default SMS manager in the Android system
Smsmanager Manager = Smsmanager . Getdefault ();
// If the text message content is too long, split the text message content
Arraylist < String > Texts = Manager . Dividemessage ( Content );
For ( String Text : Texts ){
// The first parameter is the recipient's mobile phone number.
// The second parameter is the SMS center number, which is generally set to null.
// The third parameter is the text message content.
// The fourth parameter: sentintent determines whether the text message is successfully sent. If you do not have a SIM card or the network is interrupted, you can use this intent to determine.
// Note whether the "send" action is successful. In other words
// The Fifth parameter: The deliveryintent is received when the text message is sent to the recipient. That is, the result after "sending" is emphasized.
// This means that sentintent and deliveryintent are activated only when the message "sent successfully" and "received by the recipient. This is equivalent to the delay in intent execution.
Manager . Sendtextmessage ( Mobile , Null , Text , Null , Null );
}
// Toast. maketext (getapplicationcontext (), "sent successfully", Toast. length_long). Show ();
Toast . Maketext ( Mainactivity . This , "Sent successfully" , Toast . Length_long ). Show ();
}

The pendingintent object used in this example has the following features: When a pendingintent object is received, the broadcast action is performed, just like the context. the sendbroadcast () method is the same, that is why it is stored in smsmanager. in the sendtextmessage () method, the pendingintent must be input as one of the parameters of the shipping service.

In the main program, the method of sending text messages only shows one of the three methods that can be used to send text messages in the smsmanager class, and the complete three available methods, see Table 5-1.

Table 5-1 three methods available in the smsmanager class

Method Name

Input parameter count

Use-Time Machine

Senddatamessage

String destinationaddress, string scaddress, short DESTIN-
Ationport, byte [] data, pendingintent sentintent, pending
Intent deliveryintent

Send data-format SMS to specific program Port

Sendmultiparttextmessage

String destinationaddress, string scaddress, arraylist
<String> parts, arraylist <pendingintent> sentintents,
Arraylist <pendingintent> deliveryintents

Send multiple text messages

Sendtextmessage

String destinationaddress, string scaddress, string text,
Pendingintent sentintent, pendingintent deliveryintent

Send text message

 

In addition, this example does not implement the part that receives the SMS. Only the text message is sent. Because the simulator that runs the program alone, you cannot know whether the text message is actually sent, and whether the recipient has actually received it. Therefore, in the process of program development, the reader can use the following tips to open two simulators, one for transmission and the other for the simulation test of the receiver.

Step 1: first go to eclipse and compile to run the program, and start the first simulator instance smoothly ).

Step 2: Open the DOS window (CMD) and enter the command to enter the folder:

D:/> Cd D:/SDK/Android/tools/

Step 3: Enter shell command, where foo is the AVD name.

D:/SDK/Android/tools> emulator-data foo

At this time, the window will jump out of another simulator. By entering the instanceid (for example, 5546) in the upper left corner as the recipient's phone number, you can test the delivery status of the SMS.

Finally, we mentioned splitting text messages. In this example, although we made a simple judgment on the number of character strings, we can only accept single text messages. In fact, there is still a public method in smsmanager:

Public arraylist <string> dividemessage (string text)

 

 

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.