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





                                        

Thursday, April 11, 2013

Accessing Inbox In Android

In Android we can Access all the SMS stored in Inbox.
we can also fetch the Sender Number, Data, Time SMS Body etc.

we use ContentResolver to query the Inbox table


 Access Inbox:


Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);

    String senderNumber=cursor.getString(cursor.getColumnIndex("address"));
           
    String smsBody=cursor.getString(cursor.getColumnIndex("body"));
           
    String dateTime=cursor.getString(cursor.getColumnIndex("date"));



SharedPreferences In Android

In Android there are 3 ways to store/save the data.

1:  Using Database (Creating table)      See Here How to create Database
2: Using Files
3: Using  SharedPreferences

SharedPreferences


SharedPreferences  Store private primitive data in key-value pairs.
The SharedPreferences class provides a way  that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).


How To Use SharedPreferences:


Get the SharedPreference


SharedPreferences  shfObject = getSharedPreferences("NAME", Context.MODE_PRIVATE); 

Writting Data to SharedPreferences:


We can write boolean, char, String, Int, long or  any type of Data to SharedPreferences and get back the value.

As already discussed that SharedPreferences store data in key value pair.


To write data  to SharedPreference we need  to use  SharedPreferences.Editor    class.

 SharedPreferences.Editor  shfEditorObject=shfObject.edit();

The general format is  to store data in     SharedPreference

shfEditorObject .putDataType("KEYNAME", "VALUE"); 

and do not forget to commit the changes made in SharedPrefenrence by using commit method.

shfEditorObject.commit();
To write a boolean:

shfEditorObject.putBoolean(key, value)
 shfEditorObject.commit();


To write an Int:

shfEditorObject.putInt(key, value)
 shfEditorObject.commit();

To write a String:

shfEditorObject.putString(key, value);
 shfEditorObject.commit();

To write a long:

shfEditorObject.putLong(key, value);
 shfEditorObject.commit();

To write a float:

shfEditorObject.putFloat(key, value);
 shfEditorObject.commit();

Fetch/Retrieve data from  SharedPreferences:


get the   SharedPreferences   with exact same SharedPreferences "NAME"  supplied to store the value

SharedPreferences  shfObject = getSharedPreferences("NAME", Context.MODE_PRIVATE); 

Stored data is fetch using SharedPreference Object, here we will use shfObject to get the data Stored in SharedPreference

the general format is :

shfObject.getDataType("KEY", defaultedValue);

Please note that the above method return the defaultedValue  if "KEY" does not exist.


To get a boolean value

shfObject.getBoolean(key, defaultValue)



To get an Int value

shfObject.getInt(key, defaultValue)

To get a Long value

shfObject.getLong(key, defaultValue)

To get a String value

shfObject.getString(key, defaultValue)

To get a Float value

shfObject.getFloat(key, defaultValue)



SharedPreferences can be used in the  all the Activities, Broadcast Receivers  within an Application.