Thursday, April 18, 2013

How To Send SMS in Android

Till now I  believe that you are familiar with android view like TextView,EditText,Buttons etc. Now we will develop some application that will do sometthing useful.

In this tutotial we learn how to send SMS from one device to another.

In android we use SMS Manager  class to send a SMS and to perform all activities related to SMS.

In android we need  permission to send SMS , we use  "android.permission.SEND_SMS"  permission to send SMS so do not forget to include this permission in manifest file

Note: all the permisssion are declared in manifest file.

Now create a new Project and start.

Editing .xml file
Edit your .xml file , add two Edittext and one Button
First Edittext to enter the PhoneNumber to whom we have to send the SMS
Second EditText to enter  the SMS Body.
And A Button to Send SMS.




</manifest><?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" >


    <TextView

        android:layout_width="fill_parent"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_height="wrap_content"

        android:text="Enter the phone number of recipient"

        android:text="Enter the phone number of recipient" />


    <EditText

        android:id="@+id/txtPhoneNo"

        android:id="@+id/txtPhoneNo"

        android:layout_width="fill_parent"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_height="wrap_content" />


    <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="Message" />

android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Message"


    <EditText

        android:id="@+id/txtMessage"

        android:id="@+id/txtMessage"

        android:layout_width="fill_parent"

        android:layout_width="fill_parent"

        android:layout_height="150px"

        android:layout_height="150px"

        android:gravity="top"

        android:gravity="top" />


    <Button

        android:id="@+id/btnSendSMS"

        android:id="@+id/btnSendSMS"

        android:layout_width="fill_parent"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_height="wrap_content"

        android:text="Send SMS"

        android:text="Send SMS" />


</LinearLayout>


DO Not forget to add the permission in manifest file, Manifest file should look like
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  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>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>



Activity File:


public class SMS extends Activity 
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
 
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);
 
        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {                
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();                 
                if (phoneNo.length()>0 && message.length()>0)                
                    sendSMS(phoneNo, message);                
                else
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });        
    }    
To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly instantiate this class; instead you will call the getDefault() static method to obtain an SmsManager object. The sendTextMessage()method sends the SMS message with a PendingIntent. The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending the message, you can use a PendingIntent object to display another activity. In this case, the PendingIntent object (pi) is simply pointing to the same activity (SMS.java), so when the SMS is sent, nothing will happen.


If you need to monitor the status of the SMS message sending process, you can actually use two PendingIntentobjects together with two BroadcastReceiver objects, like this:




private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
 
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
 
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
 
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));
 
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        
 
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
    }


The above code uses a PendingIntent object (sentPI) to monitor the sending process. When an SMS message is sent, the first BroadcastReceiver's onReceive event will fire. This is where you check the status of the sending process. The second PendingIntent object (deliveredPI) monitors the delivery process. The second BroadcastReceiver's onReceiveevent will fire when an SMS is successfully delivered.



Hope You Enjoyed it . Comments and Questions are welcome.

To Learn How To Receice SMS read How to Recieve SMS





                                        

No comments:

Post a Comment