SmsManager

Android: How to send SMS message

A very useful feature in Android is the SmsManager API which you can use to send an SMS from inside your own Application. Actually there are two way you can send an SMS from your Application:

  • Using SmsManager API
  • Using the build in SMS activity of Android API
Using the built in Application is fairly easy, because you don’t have to do anything special really. You just have to call the built in Activity. But using the SmsManager API, you can customize your own Activity the way you want and use it in any manner you choose, so it’s much more flexible. So, in this tutorial we are going to examine both ways.

For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project and click Next.

You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

Send an SMS using the SmsManager API

1. Create the main Layout of the Application

Open res/layout/main.xml file :

And paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/phoneNum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Phone Number : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editPhoneNum"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="phone" >
    </EditText>

    <TextView
        android:id="@+id/SMSLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter SMS Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:lines="5"
        android:gravity="top" />

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send" />

</LinearLayout>

Now you may open the Graphical layout editor to preview the User Interface you created:

2. Set the SMS Permissions in AndroidManifest.xml 

Go to AndroidManifest.xml

And paste the following code in order to set the appropriate SMS permission for the Application:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javacodegeeks.android.androidsmsexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.javacodegeeks.android.androidsmsexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3. Code

Go to the java file that contains the code of the activity you’ve just created:

And paste the following code:

package com.javacodegeeks.android.androidsmsexample;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	Button button;
	EditText editPhoneNum;
	EditText editSMS;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		button = (Button) findViewById(R.id.button);
		editPhoneNum = (EditText) findViewById(R.id.editPhoneNum);
		editSMS = (EditText) findViewById(R.id.editSMS);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String phoneNo = editPhoneNum.getText().toString();
				String sms = editSMS.getText().toString();

				try {
					SmsManager smsManager = SmsManager.getDefault();
					smsManager.sendTextMessage(phoneNo, null, sms, null, null);
					Toast.makeText(getApplicationContext(), "SMS Sent!",
							Toast.LENGTH_LONG).show();
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(),
							"SMS faild, please try again later!",
							Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}

			}
		});
	}
}

4. Run the application

This is the main screen of our Application:

When you tap in the Phone Number, the numeric keypad pops up:

Now, when you tap in the SMS Message, the character keypad pops up:

And if you press “Send”, your message will be sent in the number you specified. If not, a popup message will inform you about the mistake.

Download Eclipse Project

This was an Android SMS Example. Download the Eclipse Project of the first part of this tutorial: AndroidSMSExample_1.zip

Send an SMS using the Built-in SMS application

For this part you can go ahead and create a new Android Project if you want, but I’m just going to use the old one.

1. Create the main Layout of the Application

Open res/layout/main.xml file :

And paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send" />

</LinearLayout>

2. Code

Go to the java file that contains the code of the activity you’ve just created:

And paste the following code:

package com.javacodegeeks.android.androidsmsexample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	Button button;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		button = (Button) findViewById(R.id.button);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				try {

					Intent smsIntent = new Intent(Intent.ACTION_VIEW);
					smsIntent.putExtra("sms_body", "JavaCodeGeeks");
					smsIntent.setType("vnd.android-dir/mms-sms");
					startActivity(smsIntent);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "SMS faild!",
							Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
			}
		});
	}
}

As you can see when the “Send” button is clicked, the build in SMS Activity will be launched.

3. Run the application

This is the main screen of our Application:

When you press Send, a new Activity will be launched:

Download Eclipse Project

This was an Android SMS Example. Download the Eclipse Project of the first part of this tutorial: AndroidSMSExample_2.zip

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button