Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Week 11 Theory – Sending SMS Messages; Getting Feedback; Sending E-mail

Week 11 – Messaging: SMS and Email · 80 min read · 25 MCQs to check yourself

Coding in Flow – How to send an email via intent

How to send SMS using an intent

Text and data sharing with implicit intents (ACTION_SEND) – Hindi/Urdu

1. SMS basics

SMS (Short Message Service) sends short text messages over the cellular network (GSM/LTE signalling, via the operator's SMSC – Short Message Service Centre). Characteristics:

Android apps can send SMS in two ways:

Method How Permission User confirms?
Implicit intent (recommended) Opens the default Messages app with number and text pre-filled None Yes – user presses Send
SmsManager API App sends the SMS directly in the background SEND_SMS (dangerous, runtime) No

2. Sending SMS with an intent

private void composeSms(String phone, String message) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("smsto:" + phone));     // only SMS apps handle smsto:
    intent.putExtra("sms_body", message);
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, "No SMS app found", Toast.LENGTH_SHORT).show();
    }
}

3. Sending SMS programmatically with SmsManager

<uses-permission android:name="android.permission.SEND_SMS" />
<uses-feature android:name="android.hardware.telephony" android:required="false" />
// 1. request the permission at run time (dangerous permission)
private final ActivityResultLauncher<String> smsPermission =
        registerForActivityResult(new ActivityResultContracts.RequestPermission(), granted -> {
            if (granted) sendDirect();
            else Toast.makeText(this, "SMS permission denied", Toast.LENGTH_SHORT).show();
        });
// on button click: smsPermission.launch(Manifest.permission.SEND_SMS);

// 2. send
private void sendDirect() {
    SmsManager sms = (Build.VERSION.SDK_INT >= 31)
            ? getSystemService(SmsManager.class) : SmsManager.getDefault();
    String text = "Your MAD lab is at 10 am";
    ArrayList<String> parts = sms.divideMessage(text);          // handles long messages
    sms.sendMultipartTextMessage("03001234567", null, parts, null, null);
    // single short message: sms.sendTextMessage(phone, null, text, sentPI, deliveredPI);
}

sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent)

Parameter Meaning
destinationAddress Recipient's phone number
scAddress SMS centre number – null = default
text Message body
sentIntent PendingIntent broadcast when the message is sent (or fails)
deliveryIntent PendingIntent broadcast when the recipient's phone receives it

Testing: two emulators can text each other – the number is the emulator's console port (e.g. 5554). Real SMS from a real phone may cost money.

4. Getting feedback after sending

Users must know what happened after an action. "Getting feedback" in messaging means (a) receiving sent and delivery reports from the system and (b) showing feedback in the UI.

(a) Sent and delivery reports with PendingIntents and a BroadcastReceiver

final String SENT = "SMS_SENT", DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
        new Intent(SENT).setPackage(getPackageName()), PendingIntent.FLAG_IMMUTABLE);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
        new Intent(DELIVERED).setPackage(getPackageName()), PendingIntent.FLAG_IMMUTABLE);

BroadcastReceiver sentReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context c, Intent i) {
        String msg;
        switch (getResultCode()) {
            case Activity.RESULT_OK: msg = "SMS sent"; break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE: msg = "Generic failure"; break;
            case SmsManager.RESULT_ERROR_NO_SERVICE: msg = "No service"; break;
            case SmsManager.RESULT_ERROR_RADIO_OFF: msg = "Radio (airplane mode) off"; break;
            case SmsManager.RESULT_ERROR_NULL_PDU: msg = "Null PDU"; break;
            default: msg = "Error " + getResultCode();
        }
        Toast.makeText(c, msg, Toast.LENGTH_SHORT).show();
    }
};
BroadcastReceiver deliveredReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context c, Intent i) {
        Toast.makeText(c, getResultCode() == Activity.RESULT_OK ? "SMS delivered" : "SMS not delivered",
                Toast.LENGTH_SHORT).show();
    }
};
// register in onStart / onResume, unregister in onStop / onPause
ContextCompat.registerReceiver(this, sentReceiver, new IntentFilter(SENT), ContextCompat.RECEIVER_NOT_EXPORTED);
ContextCompat.registerReceiver(this, deliveredReceiver, new IntentFilter(DELIVERED), ContextCompat.RECEIVER_NOT_EXPORTED);

sms.sendTextMessage(phone, null, text, sentPI, deliveredPI);

(b) UI feedback techniques

Technique When
Toast Short, non-interactive confirmation ("SMS sent")
Snackbar Message with an action ("Message deleted – UNDO")
AlertDialog Confirmation before an important action ("Send to 40 students?")
ProgressBar / progress indicator While waiting (sending, uploading)
Notification Result when the user is outside the app
setError on EditText Invalid input (empty number)
Haptic feedback / vibration Physical feel of a tap
Disabled button / changed text Prevent double sending ("Sending…")

Receiving SMS (concept)

Apps can receive incoming SMS with a receiver for SMS_RECEIVED and the RECEIVE_SMS permission – but Google Play restricts this to default SMS apps. For OTP verification use the SMS User Consent API or SMS Retriever API (Google Play services) which need no SMS permission.

5. Sending email

Android apps normally do not send email themselves; they hand the message to an email app (Gmail, Outlook) using an intent:

private void composeEmail(String to, String subject, String body) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:"));                          // only email apps
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{to});          // must be an ARRAY
    intent.putExtra(Intent.EXTRA_CC, new String[]{"hod@uni.edu.pk"});
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, body);
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, "No email app", Toast.LENGTH_SHORT).show();
    }
}
Extra Content
EXTRA_EMAIL Array<String> of recipients (To)
EXTRA_CC, EXTRA_BCC Arrays of CC/BCC recipients
EXTRA_SUBJECT Subject line
EXTRA_TEXT Body text
EXTRA_STREAM Attachment URI (use ACTION_SEND + type + FileProvider URI)

ACTION_SENDTO vs ACTION_SEND

ACTION_SENDTO with mailto: ACTION_SEND
Only email apps are offered Any sharing app (WhatsApp, Drive, Bluetooth…)
Best for "Contact us/Feedback" Best for sharing, and needed for attachments
No MIME type needed Requires type e.g. "text/plain", "message/rfc822", "application/pdf"

Sending email in the background (without user)

Requires your own server or an email API (SMTP over a backend, SendGrid, Firebase extension); putting an SMTP password inside the app is insecure – never do it.

6. Permissions and policies for messaging

Permission Type Use
SEND_SMS Dangerous – runtime request Sending SMS via SmsManager
RECEIVE_SMS, READ_SMS Dangerous + Play policy restricted Only default SMS/phone apps or approved exceptions
CALL_PHONE Dangerous Direct calls
INTERNET Normal – granted at install Network access
POST_NOTIFICATIONS Runtime (Android 13+) Notifications

Runtime permission flow (Android 6.0+)

  1. Declare the permission in the manifest.
  2. Check: ContextCompat.checkSelfPermission(ctx, perm) == PERMISSION_GRANTED.
  3. If not granted, optionally explain why (shouldShowRequestPermissionRationale), then request with the Activity Result API (RequestPermission).
  4. Handle the result: proceed if granted; degrade gracefully if denied; if permanently denied, guide the user to app Settings.

Google Play SMS/Call Log policy: apps may request SMS or Call Log permissions only if they are the default SMS/phone handler or fit approved use cases (e.g. backup); otherwise use intents. This is why intents are the recommended way for normal apps.

Short and long questions

1. Explain the parameters of SmsManager.sendTextMessage().

Model answer

destinationAddress – recipient number; scAddress – service-centre number (null for default); text – message body; sentIntent – PendingIntent broadcast when the message is sent or fails; deliveryIntent – PendingIntent broadcast when it is delivered to the recipient.

2. List five ways of giving feedback to the user.

Model answer

Toast, Snackbar (with undo action), AlertDialog (confirmation), ProgressBar or progress indicator while waiting, notification when outside the app, and setError on invalid fields (also disabling the button or haptic feedback).

3. Compare sending SMS by intent and by SmsManager.

Model answer

Intent: opens the default Messages app with the number and text pre-filled, needs no permission and the user presses Send. SmsManager: sends directly from the app in the background, needs the dangerous SEND_SMS runtime permission (and is restricted by Play policy), and can report sent/delivery status through PendingIntents.

4. How can an app know whether an SMS was sent and delivered?

Model answer

Pass sent and delivery PendingIntents (created with PendingIntent.getBroadcast for custom actions) to sendTextMessage and register BroadcastReceivers for those actions; in onReceive check resultCode – RESULT_OK means sent/delivered, otherwise codes such as RESULT_ERROR_NO_SERVICE or RESULT_ERROR_RADIO_OFF indicate failure.

5. Differentiate between ACTIONSENDTO and ACTIONSEND for email.

Model answer

ACTION_SENDTO with a mailto: URI offers only email apps and needs no MIME type – ideal for "contact us". ACTION_SEND requires a MIME type and offers all apps that can share that type (WhatsApp, Drive etc.); it is needed for attachments through EXTRA_STREAM.

6. Describe the runtime permission flow in Android.

Model answer

Declare the permission in the manifest; check it with ContextCompat.checkSelfPermission; if not granted, optionally show a rationale (shouldShowRequestPermissionRationale) and request it using registerForActivityResult(RequestPermission()); in the callback continue if granted, otherwise disable the feature or guide the user to Settings.

7. Write the code to compose an email with recipient, subject and body.

Model answer

Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")); i.putExtra(Intent.EXTRA_EMAIL, new String[]{"cs@uni.edu.pk"}); i.putExtra(Intent.EXTRA_SUBJECT, "Leave application"); i.putExtra(Intent.EXTRA_TEXT, "Respected sir..."); startActivity(i);

8. Write Java code to open the Messages app with a number and text filled in.

Model answer

Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:03001234567")); i.putExtra("sms_body", "Hello"); startActivity(i); – wrapped in try/catch for ActivityNotFoundException.

9. Explain the two ways of sending SMS from an Android app. Write complete code to send an SMS using SmsManager with runtime permission and get feedback when the message is sent and delivered.

Model answer

1. Intent method: Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone)).putExtra("sms_body", text) opens the default Messages app; no permission; the user presses Send. Recommended for normal apps and allowed by Play policy.

2. SmsManager method: sends directly from the app.

  • Manifest: uses-permission SEND_SMS (and uses-feature android.hardware.telephony required=false).
  • Runtime permission: ActivityResultLauncher<String> launcher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), ok -> { if (ok) send(); });, then launcher.launch(Manifest.permission.SEND_SMS); after checking checkSelfPermission.
  • Feedback intents: PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT").setPackage(getPackageName()), PendingIntent.FLAG_IMMUTABLE); and similarly deliveredPI for "SMS_DELIVERED".
  • Receivers: a BroadcastReceiver for SMS_SENT whose onReceive checks getResultCode() (RESULT_OK = sent; RESULT_ERROR_GENERIC_FAILURE, RESULT_ERROR_NO_SERVICE, RESULT_ERROR_NULL_PDU, RESULT_ERROR_RADIO_OFF = failures) and shows a Toast; another for SMS_DELIVERED (RESULT_OK = delivered). Register them with ContextCompat.registerReceiver(..., RECEIVER_NOT_EXPORTED) in onStart and unregister in onStop.
  • Send: SmsManager sms = getSystemService(SmsManager.class); (API 31+) or SmsManager.getDefault(); sms.sendTextMessage(phone, null, text, sentPI, deliveredPI); for long texts sms.sendMultipartTextMessage(phone, null, sms.divideMessage(text), sentList, deliveredList).
  • UI feedback: disable the Send button and show "Sending…", then a Toast/Snackbar with the result; setError for an empty number.

Testing between two emulators uses the port number (5554) as the phone number. Delivery reports depend on the network operator.

10. How are emails sent from an Android application? Explain the intent extras, compare ACTIONSENDTO and ACTIONSEND, show how to add an attachment, and discuss why apps should not send email directly with SMTP.

Model answer

Android apps normally compose an email and let an installed email app (Gmail, Outlook) send it, using an implicit intent. ACTION_SENDTO with Uri.parse("mailto:") ensures only email apps respond. Extras: EXTRA_EMAIL – array of To addresses; EXTRA_CC and EXTRA_BCC – arrays; EXTRA_SUBJECT – subject; EXTRA_TEXT – body. Example: Intent i = new Intent(Intent.ACTION_SENDTO); i.setData(Uri.parse("mailto:")); i.putExtra(Intent.EXTRA_EMAIL, new String[]{"cs@uni.edu.pk"}); i.putExtra(Intent.EXTRA_SUBJECT, "Feedback"); i.putExtra(Intent.EXTRA_TEXT, body); then startActivity(i) in try/catch.

ACTION_SEND requires a MIME type (text/plain, message/rfc822, application/pdf) and opens a chooser of all apps that accept that type; it is used for general sharing and for attachments: put the file's FileProvider content URI in EXTRA_STREAM and add FLAG_GRANT_READ_URI_PERMISSION.

Feedback: after the email app returns, show a Toast/Snackbar such as "Opening email app" or "Thank you for your feedback"; validate fields first with setError.

Why not SMTP inside the app: sending automatically would require embedding SMTP credentials or API keys in the APK, which can be extracted by decompiling, leading to spam and account abuse; it also bypasses user consent. Automatic emails (receipts, verification) should be sent by a secure backend server or email service (SendGrid, Firebase extensions) that the app calls through an authenticated API.

This lesson ends with a quiz of 25 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Week 10 Lab 10 – Store and Retrieve a Username Using SharedPreferences · Next: Week 11 Lab 11 – Open the SMS or Email Application with Prefilled Text

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester