Keywords: Android | Intent | SMS_Sending
Abstract: This article provides an in-depth analysis of two primary methods for sending SMS messages via Intent in Android applications: launching the native SMS composer and sending directly from within the app. It examines the differences between ACTION_VIEW and ACTION_SENDTO, explains common error causes, and offers complete code examples with best practices. The discussion focuses on permission management, data format handling, and compatibility across Android versions, helping developers avoid common pitfalls and implement reliable SMS functionality.
Introduction and Problem Context
In Android development, sending SMS messages via Intent is a common functional requirement that allows applications to leverage the system's existing SMS handling capabilities. However, developers often encounter various issues when implementing this feature, particularly when using incorrect Intent configurations that may lead to the app redirecting to wrong contact interfaces or failing to send messages properly. This article systematically analyzes and resolves these problems based on high-quality Q&A data from Stack Overflow.
Fundamental Principles of SMS Sending via Intent
The Android system implements inter-component communication through the Intent mechanism, with SMS sending functionality primarily relying on two Intent actions: Intent.ACTION_VIEW and Intent.ACTION_SENDTO. The core distinction between these methods lies in how they handle data URIs and the behavioral patterns of system responses.
When using ACTION_VIEW, the system attempts to open the SMS application in viewing mode, which may result in unexpected contact selection interfaces on certain devices. In contrast, ACTION_SENDTO explicitly instructs the system to launch the SMS sending interface, typically providing a more consistent experience. Understanding this difference is crucial for avoiding common errors.
Method One: Launching the Native SMS Composer
This approach allows users to edit and send SMS messages within the system's SMS application, with the app itself not directly handling the sending process. Its main advantage is that it doesn't require the SEND_SMS permission, simplifying permission management and enhancing user privacy protection.
Below is a complete implementation example, including both layout file and Activity code:
Layout File (main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/btnSendSMS"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Send SMS"
android:layout_centerInParent="true"
android:onClick="sendSMS">
</Button>
</RelativeLayout>Activity Code
public class SendSMSActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void sendSMS(View v)
{
String number = "12346556";
startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));
}
}Alternatively, an implementation using ACTION_SENDTO:
public void sendSMS(View v)
{
Uri uri = Uri.parse("smsto:12346556");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "Here you can set the SMS text to be sent");
startActivity(it);
}The key to this method lies in correctly constructing the URI: using the sms: or smsto: prefix followed by the phone number. Pre-setting SMS content via putExtra("sms_body", message) is possible, though users retain the opportunity to modify it before sending.
Method Two: Sending SMS Directly from Within the App
This method requires the app to directly handle SMS sending logic, necessitating the declaration of the SEND_SMS permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.SEND_SMS" />Implementation typically involves using the SmsManager API:
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);While this approach offers complete control, it requires handling runtime permission requests (Android 6.0+) and more complex error handling logic. As this article primarily focuses on Intent methods, detailed implementation can be referenced from external technical blogs.
Common Problem Analysis and Solutions
The erroneous code mentioned in the original question:
Intent intentt = new Intent(Intent.ACTION_VIEW);
intentt.setData(Uri.parse("sms:"));
intentt.setType("vnd.android-dir/mms-sms");
intentt.putExtra(Intent.EXTRA_TEXT, "");
intentt.putExtra("address", phone number);
context.startActivity(intentt);Contains several issues:
- Simultaneously setting
setData()andsetType()clears previously set data, causing URI information loss - Using
EXTRA_TEXTinstead ofsms_bodymay result in content not being correctly recognized - Phone numbers should be included directly in the URI rather than passed as extras
Correct Intent configuration should adhere to the single responsibility principle: either pass all necessary information via the URI or use extras, but avoid mixing approaches to prevent conflicts.
Advanced Techniques and Best Practices
1. URI Format Standardization: Always use Uri.parse("smsto:" + phoneNumber) or Uri.fromParts("sms", phoneNumber, null) to ensure compatibility.
2. Intent Flag Usage: In certain scenarios, adding Intent.FLAG_ACTIVITY_NEW_TASK ensures the SMS application launches in a new task stack, preventing unexpected behaviors upon return.
3. Error Handling: Wrap startActivity() calls in try-catch blocks to handle ActivityNotFoundException and provide user-friendly feedback when no SMS application is available on the device.
4. Multi-Version Compatibility: Different Android versions have slight variations in SMS Intent support; thorough testing on major versions is recommended.
Performance and Security Considerations
While convenient, sending SMS via Intent requires attention to performance impacts: each call launches an external application, potentially increasing memory overhead. Security-wise, Method One reduces sensitive permission requirements by not directly sending SMS, but Method Two necessitates careful handling of SMS content to avoid user privacy leaks.
It is advisable to use Intent methods for non-critical paths and consider direct SmsManager usage with retry mechanisms for scenarios requiring reliable sending.
Conclusion
Sending SMS via Intent is a practical technique in Android development. Properly understanding the differences between ACTION_VIEW and ACTION_SENDTO, mastering URI construction methods, and avoiding common configuration errors are key to implementing stable functionality. The two methods presented in this article each have suitable application scenarios, and developers should choose based on specific requirements. As the Android system evolves, continuous monitoring of official documentation updates is recommended to ensure forward compatibility of implementations.