Android send short message method example detail

  • 2021-01-25 07:54:41
  • OfStack

This article illustrates the Android method for sending SMS messages. To share with you for your reference, as follows:

SMS and phone calls are both basic functions of android mobile phones. The following examples illustrate how android can send SMS.

The procedure is as follows:


import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class A03Activity extends Activity {
 private EditText et01,et02;
 private Button b;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    et01=(EditText)findViewById(R.id.et01);
    et02=(EditText)findViewById(R.id.et02);
    b=(Button)findViewById(R.id.b);
    b.setBackgroundColor(Color.GREEN);
    b.setText(" send ");
    et01.setText(" Please enter the telephone number ");// The original EditText The hints inside 
    et02.setText(" Please enter the text message content ");
    // The following EditText THE EDIT () METHOD DISAPPEARS WHEN THE ORIGINAL CONTENTS OF THE EDIT BOX ARE CLICked 
    et01.setOnClickListener(new OnClickListener(){
  @Override
  public void onClick(View v) {
  // TODO Auto-generated method stub
  et01.setText("");
  }
    });
    et02.setOnClickListener(new OnClickListener(){
  @Override
  public void onClick(View v) {
  // TODO Auto-generated method stub
  et02.setText("");
  }
    });
    //Button  the setOnClickListener() The send SMS () method triggers the send SMS event 
    b.setOnClickListener(new OnClickListener(){
  @Override
  public void onClick(View v) {
  // TODO Auto-generated method stub
  String s01=et01.getText().toString();
  String s02=et02.getText().toString();
  // achieve 1 Of the default instances SmsManager
  SmsManager sm=SmsManager.getDefault();
  if(isPhoneNumberValid(s01)&&isWithin70(s02)){
   /**
   *  Send text messages when both criteria pass, build first 1 a PendingIntent Object and use the getBroadcast() radio 
   *  then PendingIntent , text messages, phone numbers and other content in SmsManager the sendTextMessage() In the method */
   try {
   PendingIntent pi=PendingIntent.getBroadcast(A03Activity.this, 0, new Intent(), 0);
   sm.sendTextMessage(s01, null, s02, pi, null);
   } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   }
   Toast.makeText(A03Activity.this, " SMS sent successfully ", Toast.LENGTH_LONG).show();
  }
  else{
   if(isPhoneNumberValid(s01)==false){
   if(isWithin70(s02)==false){
    Toast.makeText(A03Activity.this, " Incorrect format for phone number! SMS content exceeds 70 A word! Please correct!! ", Toast.LENGTH_LONG).show();
   }
   else{
    Toast.makeText(A03Activity.this, " Incorrect format for phone number! Please correct!! ", Toast.LENGTH_LONG).show();
   }
   }
   else{
   if(isWithin70(s02)==false){
    Toast.makeText(A03Activity.this, " SMS content exceeds 70 A word! Please correct ", Toast.LENGTH_LONG).show();
   }
   }
  }
  }
    });
  }
  // Determine if the text message content exceeds 70 A word 
  public static boolean isWithin70(String s){
   if(s.length()>70){
   return false;
   }
   else{
   return true;
   }
  }
  // Determine whether the telephone number is in the correct format 
  public static boolean isPhoneNumberValid(String phoneNumber){
   boolean valid=false;
   /**
   *  Two telephone number formats 
   * ^\\(?  It can be expressed as ( At the beginning 
   * (\\d{3})  Means to follow closely 3 A digital 
   * \\)?  It can be expressed as ) Continue to 
   * [- ]?  Indicates that an optional "can be used after the above format - "To continue 
   * (\\d{4})  Means to follow closely 4 A digital 
   * [- ]?  Indicates that an optional "can be used after the above format -" Continue to  
   * (\\d{4})$  Said to 4 The end of the number 
   *  To sum up: the correct telephone number format can be used as a reference: 
   * (123)456-78900 123-456-78900 12345678900 (123)-456-78900*/
   String expression01="^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
   String expression02="^\\(?(\\d{3})\\)?[- ]?(\\d{5})[- ]?(\\d{5})$";
   // create Pattern object 
   Pattern p01=Pattern.compile(expression01);
   // will Pattern Passing in as a parameter Matcher , as a phone number phoneNumber The correct format of 
   Matcher m01=p01.matcher(phoneNumber);
   Pattern p02=Pattern.compile(expression02);
   Matcher m02=p02.matcher(phoneNumber);
   if(m01.matches()||m02.matches()){
   valid=true;
   }
   else{
   valid=false;
   }
 return valid;
  }
}

AndroidManifest. xml as follows:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.my.a03"
  android:versionCode="1"
  android:versionName="1.0" >
  <uses-sdk android:minSdkVersion="10" />
  <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
      android:name=".A03Activity"
      android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
  <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
</manifest>

When the PendingIntent object is received, the broadcast action is performed, just like the Context.sendBroadcast() method 1, which is why the SmsManager.sendTextMessage() method needs to pass PendingIntent as one of the parameters of the service.

If you don't have an android 2.3.3 smartphone nearby, you can open two android emulators, one to send and one to receive messages:

1. First compile and run this program with Eclipse, and then open the first emulator

2. Open the DOS window (cmd) and type the following command:

D:\>cd D:\SDK\android\tools\

3. Enter shell command

D:\SDK\android\tools>emulator  -data  foo

After these steps, a second simulator appears. InstanceID(e.g., 5546) at the top left is used as the recipient's phone number to test the delivery status of SMS messages.

Sometimes our text messages are more than 70 words long, and we don't want to type in paragraphs, we want to just type them out and let the phone automatically break them into 70-word messages. How do we do that?

This is where one of the SmsManager methods is used:

public ArrayList<String> divideMessage(String text)

When the content of the message exceeds 70 words, this method will automatically help us to divide the message into several short messages of no more than 70 words, and the return type of the divideMessage() method is ArrayList, and then through the sendTextMessage() do a loop to send.

Finally, note that AndroidManifest has added the right to send text messages, as shown below:

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

More about Android related content interested readers can view the site: "Android control usage summary" and "Android development introductory and advanced tutorial"

Hope this article described to everybody Android program design is helpful.


Related articles: