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); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access