Recipe 5.2 Sending SMS Messages Programmatically in Your Android Application
The previous recipe showed sending SMS messages using the built-in Messaging application. That is useful if you want to present users with a familiar UI to a message. However, in some situations you might want to programmatically send SMS messages in your Android application. For example, your application might monitor the current location of a user and automatically send an SMS message to a predefined phone number, which would be very helpful if you were building an application to ensure someone’s safety, such as children or the elderly at home.
Solution
To send an SMS message programmatically from within your Android application, use the SmsManager class, available from the android.telephony.SmsManager package. The following code snippet shows how to send an SMS message to another device (emulator 5556) with the message “Greetings!”:
package net.learndevelop.sendsms;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ...
Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.