SoFunction
Updated on 2025-04-11

Example of Android programming to implement SMS sending and receiving and voice broadcast prompt functions

This article describes the Android programming to implement the functions of sending and receiving SMS and voice broadcasting prompts. Share it for your reference, as follows:

Send SMS Function Interface

/**
  * Send a text message Demo
  *
  * @description:
  * @author ldm
  * @date 2016-4-22 9:07:53 AM
  */
public class SmsActivity extends Activity implements OnClickListener {
  public static final String SMS_RECIPIENT_EXTRA = ".SMS_RECIPIENT";
  public static final String ACTION_SMS_SENT = ".SMS_SENT_ACTION";
  private Button sms_send_message;
  private EditText sms_recipient;
  private EditText sms_content;
  private CheckBox sms_enable_receiver;
  private TextView sms_status;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.send_sms_layout);
    initViews();
    initListeners();
    registerSmsReceiver();
  }
  /**
    * Register SMS Monitoring Broadcast
    *
    * @description:
    * @author ldm
    * @date 2016-4-22 9:23:23 AM
    */
  private void registerSmsReceiver() {
    registerReceiver(new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        String message = null;
        boolean error = true;
        switch (getResultCode()) {
        case Activity.RESULT_OK:
          message = "Send successfully!";
          error = false;
          break;
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
          message = "Send failed";
          break;
        case SmsManager.RESULT_ERROR_NO_SERVICE:
          message = "Send failed";
          break;
        case SmsManager.RESULT_ERROR_NULL_PDU:
          message = "Send failed";
          break;
        case SmsManager.RESULT_ERROR_RADIO_OFF:
          message = "Send failed";
          break;
        }
        sms_recipient.setEnabled(true);
        sms_content.setEnabled(true);
        sms_content.setText("");
        sms_status.setText(message);
        sms_status.setTextColor(error ?  : );
      }
    }, new IntentFilter(ACTION_SMS_SENT));
  }
  /**
    * Listen to events
    *
    * @description:
    * @author ldm
    * @date 2016-4-22 9:24:20 AM
    */
  private void initListeners() {
    sms_send_message.setOnClickListener(this);
    // Apply Package Manager    final PackageManager pm = ();
    // Get the specified component in the application    final ComponentName componentName = new ComponentName("",
        "");
    //Judge the selected state of sms_enable_receiver based on whether the component is available?    sms_enable_receiver
        .setChecked((componentName) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
    // Listen to sms_enable_receiver to set whether the broadcast component is available    sms_enable_receiver
        .setOnCheckedChangeListener(new OnCheckedChangeListener() {
          public void onCheckedChanged(CompoundButton buttonView,
              boolean isChecked) {
            // Component status settings            (
                componentName,
                isChecked ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                    : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
          }
        });
  }
  private void initViews() {
    sms_recipient = (EditText) (findViewById(.sms_recipient));
    sms_content = ((EditText) findViewById(.sms_content));
    // Whether to turn on the SMS broadcast reception switch    sms_enable_receiver = (CheckBox) findViewById(.sms_enable_receiver);
    sms_send_message = (Button) findViewById(.sms_send_message);
    sms_status = (TextView) findViewById(.sms_status);
    if (getIntent().hasExtra(SMS_RECIPIENT_EXTRA)) {
      sms_recipient.setText(getIntent().getExtras().getString(
          SMS_RECIPIENT_EXTRA));
      sms_content.requestFocus();
    }
  }
  @Override
  public void onClick(View v) {
    if (() == .sms_send_message) {
      sendSms();
    }
  }
  /**
    * sending a text message
    *
    * @description:
    * @author ldm
    * @date 2016-4-22 9:30:38 am
    */
  private void sendSms() {
    if ((sms_recipient.getText())) {
      (, "Please enter the SMS recipient", Toast.LENGTH_SHORT)
          .show();
      return;
    }
    if ((sms_content.getText())) {
      (, "Please enter the text message", Toast.LENGTH_SHORT)
          .show();
      return;
    }
    sms_recipient.setEnabled(false);
    sms_content.setEnabled(false);
    SmsManager sms = ();
    List<String> messages = (sms_recipient.getText()
        .toString());
    String recipient = sms_content.getText().toString();
    for (String message : messages) {
      // sending a text message      (recipient, null, message, PendingIntent
          .getBroadcast(, 0, new Intent(
              ACTION_SMS_SENT), 0), null);
    }
  }
}

Post-processing interface for receiving SMS:

/**
  * Receive SMS voice broadcasts
  *
  * @description:
  * @author ldm
  * @date 2016-4-22 9:34:21 AM
  */
public class SmsReceivedActivity extends Activity implements OnInitListener {
  private static final int DIALOG_SHOW_MESSAGE = 1;
  public static final String SMS_FROM_ADDRESS_EXTRA = ".SMS_FROM_ADDRESS";
  public static final String SMS_FROM_DISPLAY_NAME_EXTRA = ".SMS_FROM_DISPLAY_NAME";
  public static final String SMS_MESSAGE_EXTRA = ".SMS_MESSAGE";
  private TextToSpeech mTts;
  private String mFromDisplayName;
  private String mFromAddress;
  private String mMessage;
  private String mFullBodyString;
  @SuppressWarnings("deprecation")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    // SMS call number    mFromAddress = getIntent().getExtras()
        .getString(SMS_FROM_ADDRESS_EXTRA);
    // Caller name    mFromDisplayName = getIntent().getExtras().getString(
        SMS_FROM_DISPLAY_NAME_EXTRA);
    mMessage = getIntent().getExtras().getString(SMS_MESSAGE_EXTRA);
    // SMS content    mFullBodyString = (getString(.sms_format),
        mFromDisplayName, mMessage);
    showDialog(DIALOG_SHOW_MESSAGE);
    //Initialize TTS    mTts = new TextToSpeech(this, this);
  }
  /**
    * Initialize TTS service
    */
  @SuppressWarnings("deprecation")
  public void onInit(int status) {
    if (status == ) {// Success status      // Set language, TTS engine supports five major languages: English, French, German, Italian and Spanish.      int result = ();
      if (result == TextToSpeech.LANG_MISSING_DATA
          || result == TextToSpeech.LANG_NOT_SUPPORTED) {
        (this, "TTS is not available", Toast.LENGTH_LONG).show();
      } else {
        (mFullBodyString, TextToSpeech.QUEUE_ADD, null);
        // (mFullBodyString, TextToSpeech.QUEUE_ADD, null,
        // "");
      }
    } else {
      (this, "TTS initialization failed", Toast.LENGTH_LONG).show();
    }
  }
  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_SHOW_MESSAGE:
      return new (this)
          .setIcon(.ic_dialog_email)
          .setTitle("Message Received")
          .setMessage(mFullBodyString)
          .setPositiveButton("reply",
              new () {
                public void onClick(DialogInterface dialog,
                    int whichButton) {
                  // Reply to the SMS message and jump to the SMS message interface to bring the recipient's message over                  Intent i = new Intent();
                  (,
                      );
                  (SmsActivity.SMS_RECIPIENT_EXTRA,
                      mFromAddress);
                  startActivity(i);
                  ();
                  finish();
                }
              })
          .setNegativeButton("Cancel",
              new () {
                public void onClick(DialogInterface dialog,
                    int whichButton) {
                  ();
                  finish();
                }
              }).create();
    }
    return null;
  }
}

SMS broadcast

/**
  * SMS to monitor the broadcast
  *
  * @description:
  * @author ldm
  * @date 2016-4-22 10:07:49 AM
  */
public class MyMsmReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    Bundle extras = ();
    if (extras == null)
      return;
    // SMS content received    Object[] pdus = (Object[]) ("pdus");
    for (int i = 0; i < ; i++) {
      SmsMessage message = ((byte[]) pdus[i]);
      String fromAddress = ();
      String fromDisplayName = fromAddress;
      Uri uri;
      String[] projection;
      uri = (
          .CONTENT_FILTER_URI,
          (fromAddress));
      projection = new String[] { .DISPLAY_NAME };
      // Query the sender of the text message      Cursor cursor = ().query(uri, projection,
          null, null, null);
      if (cursor != null) {
        if (())
          fromDisplayName = (0);
        ();
      }
      // Jump to the SMS receiving interface      Intent di = new Intent();
      (context, );
      (Intent.FLAG_ACTIVITY_NEW_TASK
          | Intent.FLAG_ACTIVITY_SINGLE_TOP);
      (SmsReceivedActivity.SMS_FROM_ADDRESS_EXTRA, fromAddress);
      (SmsReceivedActivity.SMS_FROM_DISPLAY_NAME_EXTRA,
          fromDisplayName);
      (SmsReceivedActivity.SMS_MESSAGE_EXTRA, message
          .getMessageBody().toString());
      (di);
    }
  }
}

Attached:DEMO sample code click hereDownload this site

For more information about Android related content, please check out the topic of this site:A summary of Android SMS and Telephone Operation Tips》、《Android file operation skills summary》、《Summary of Android operating json format data skills》、《Android programming activity operation skills summary》、《Android development introduction and advanced tutorial》、《Android resource operation skills summary》、《Android View View Tips Summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.