Android How to - Send SMS Messages Programmatically








The following code shows how to Send SMS Messages Programmatically.

Example

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

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

</LinearLayout>

Java code

/*from  ww w .j  a  va 2 s  .c  om*/
package com.java2s.myapplication3.app;

import android.app.Activity;
import android.os.Bundle;

import android.telephony.SmsManager;
import android.view.View;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View v) {
        sendSMS("5556", "Hello my friends!");
    }

    //sends an SMS message to another device
    private void sendSMS(String phoneNumber, String message)
    {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
    }
}

In the AndroidManifest.xml file, add the following statements:

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

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

 <application
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name" >
     <activity
         android:label="@string/app_name"
         android:name=".SMSActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

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

</manifest>




How to run

On the first Android emulator (5554), click the Send SMS button to send an SMS message to the second emulator (5556).