ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development
    EC-333
    Progress0 / 33 topics
    Topics
    1. Mobiles Application Development Platform2. HTML5 for Mobiles3. Android OS: Architecture, Framework and Application Development4. iOS: Architecture, Framework5. Application Development with Windows Mobile6. Eclipse7. Fragments8. Calling Built-in Applications using Intents9. Displaying Notifications10. Components of a Screen11. Adapting to Display Orientation12. Managing Changes to Screen Orientation13. Utilizing the Action Bar14. Creating the User Interface15. Listening for UI Notifications16. Views17. User Preferences18. Persisting & Sharing Data19. Sending SMS Messages20. Getting Feedback21. Sending E-mail22. Displaying Maps23. Consuming Web Services Using HTTP24. Web Services: Accessing and Creating25. Threading26. Publishing Android Applications27. Deployment on App Stores28. Mobile Programming Languages29. Challenges with Mobility and Wireless Communication30. Location-aware Applications31. Performance/Power Tradeoffs32. Mobile Platform Constraints33. Emerging Technologies
    EC-333›Sending SMS Messages
    Mobile Application DevelopmentTopic 19 of 33

    Sending SMS Messages

    6 minread
    1,090words
    Intermediatelevel

    Sending SMS Messages in Android

    In Android, sending SMS messages (Short Message Service) is a common feature that allows an app to send text messages to other phone numbers. This functionality can be useful in applications related to communication, authentication (like OTP verification), or notifications.

    Android provides a straightforward API to send SMS messages, but there are certain permissions and practices to consider when implementing SMS functionality.


    1. Required Permissions

    To send SMS messages in Android, you need to declare the appropriate permissions in your AndroidManifest.xml file. There are two main permissions you might need, depending on the specific functionality:

    A. Sending SMS Messages

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

    This permission allows your app to send SMS messages.

    B. Reading SMS (Optional)

    If your app needs to read incoming SMS messages (e.g., for OTP verification), you'll need the following permission:

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

    This permission is typically requested when interacting with SMS directly, such as reading messages for automatic verification.


    2. Sending SMS Using SmsManager

    The primary way to send SMS messages programmatically in Android is through the SmsManager class. This class provides methods to send SMS messages both to individual phone numbers and in bulk.

    Here’s how you can use SmsManager to send an SMS message.

    A. Sending a Simple SMS

    import android.telephony.SmsManager;
    
    public void sendSMS(String phoneNumber, String message) {
        // Get an instance of SmsManager
        SmsManager smsManager = SmsManager.getDefault();
        
        // Send the SMS
        smsManager.sendTextMessage(phoneNumber, null, message, null, null);
    }
    
    • sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent): This method sends a text message to a specified phone number.
      • destinationAddress: The phone number to which the message is sent.
      • scAddress: The service center address (usually null for standard messages).
      • text: The body of the message.
      • sentIntent: A PendingIntent to be triggered when the message is sent. If null, it won't trigger any action.
      • deliveryIntent: A PendingIntent to be triggered when the message is delivered. If null, it won't trigger any action.

    In this example, the message is sent without tracking the status of the message (i.e., no PendingIntent is provided).


    B. Sending SMS with a PendingIntent (Optional)

    You can also monitor the status of the SMS by passing a PendingIntent for both the sent and delivery statuses. This is useful if you want to handle the SMS sending result (whether it was successful or failed).

    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.telephony.SmsManager;
    
    public void sendSMSWithStatus(Context context, String phoneNumber, String message) {
        // Create PendingIntents for SMS sent and delivery status
        Intent sentIntent = new Intent("SMS_SENT");
        PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, sentIntent, 0);
    
        Intent deliveryIntent = new Intent("SMS_DELIVERED");
        PendingIntent deliveryPI = PendingIntent.getBroadcast(context, 0, deliveryIntent, 0);
        
        // Get the default SmsManager
        SmsManager smsManager = SmsManager.getDefault();
        
        // Send the SMS with PendingIntent for sent and delivery status
        smsManager.sendTextMessage(phoneNumber, null, message, sentPI, deliveryPI);
    }
    
    • PendingIntent: This is used to perform some action when the message is sent or delivered.
      • The sent intent is triggered when the message is successfully sent or when there is an error.
      • The delivery intent is triggered when the message is successfully delivered.

    You can listen for these intents in your BroadcastReceiver to handle the sent and delivery events.

    BroadcastReceiver Example:

    To handle these intents, you need to register a BroadcastReceiver to listen for the SMS sent and delivered events.

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.Toast;
    
    public class SmsReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // Check if the intent is for SMS sent or delivery status
            String action = intent.getAction();
            
            if ("SMS_SENT".equals(action)) {
                int resultCode = getResultCode();
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(context, "SMS Sent Successfully", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "SMS Failed to Send", Toast.LENGTH_SHORT).show();
                }
            } else if ("SMS_DELIVERED".equals(action)) {
                int resultCode = getResultCode();
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(context, "SMS Delivered", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "SMS Not Delivered", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    

    You need to register this receiver in your AndroidManifest.xml:

    <receiver android:name=".SmsReceiver">
        <intent-filter>
            <action android:name="SMS_SENT"/>
            <action android:name="SMS_DELIVERED"/>
        </intent-filter>
    </receiver>
    

    3. Handling Runtime Permissions (Android 6.0 and Above)

    Starting with Android 6.0 (API level 23), Android apps need to request permissions at runtime for certain sensitive operations, such as sending SMS. This means you need to check whether the app has the necessary permissions before attempting to send an SMS.

    A. Check for SEND_SMS Permission

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) 
            != PackageManager.PERMISSION_GRANTED) {
        // Permission is not granted, request permission
        ActivityCompat.requestPermissions(this, 
            new String[]{Manifest.permission.SEND_SMS}, REQUEST_SEND_SMS);
    } else {
        // Permission already granted, send SMS
        sendSMS(phoneNumber, message);
    }
    

    B. Handle Permission Result

    You also need to handle the result of the permission request in your onRequestPermissionsResult() method:

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_SEND_SMS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, send SMS
                sendSMS(phoneNumber, message);
            } else {
                // Permission denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
    

    4. Using Intent to Send SMS (Deprecated in Newer Versions)

    Another method to send SMS is by using an Intent. However, this method is deprecated in newer Android versions because it involves leaving the app to use a built-in messaging app, and it's not as flexible as SmsManager.

    Example:

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse("smsto:" + phoneNumber));  // Set recipient phone number
    intent.putExtra("sms_body", message);  // Set message body
    startActivity(intent);  // Opens the default messaging app
    
    • This approach opens the device’s default messaging app with the recipient's phone number and a pre-filled message, allowing the user to review and send the SMS manually.

    5. Conclusion

    Sending SMS messages in Android is simple and straightforward using the SmsManager class. For basic SMS functionality, you can send messages directly, while using PendingIntent allows you to track the sending and delivery status. Additionally, remember to handle runtime permissions for sending SMS on Android 6.0 and higher devices.

    If you want to offer a better user experience, consider using SMS Intent only for opening the default SMS app, and use SmsManager for background SMS sending when you need more control over the process.

    Always ensure that the app handles permissions carefully and provide feedback on the SMS sending process for a smooth user experience.

    Previous topic 18
    Persisting & Sharing Data
    Next topic 20
    Getting Feedback

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,090
      Code examples0
      DifficultyIntermediate