Skip to main content

SMS Messaging - Android Tutorial

Understanding how to use SMS Messaging in your application can provide you with many ideas to create the next killer application.

In this article, we take a look at how you can programmatically send and receive SMS messages in your Android application

Sending SMS messages

STEP-1 :

To get started, first launch Studio/Eclipse and create a new Android project(Basic Activity). Name the project as you like(mine - MrBrown-SMS)

STEP-2:

Android uses a permission-based policy where all the permissions needed by an application need to be specified in the AndroidManifest.xml file. By doing so, when the application is installed it will be clear to the user what specific access permissions are required by the application. For example, as sending SMS messages will potentially incur additional cost on the user’s end, indicating the SMS permissions in the AndroidManifest.xml file will let the user decide whether to allow the application to install or not.

In the AndroidManifest.xml file, add the two permissions – SEND_SMS and RECEIVE_SMS:

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


STEP-3:

Create send.xml file located in the res/layout folder, add the following code so that the user can enter a phone number as well as a message to send:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"        
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bgcomsms"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<LinearLayout
android:id="@+id/idLn"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/idback"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:src="@drawable/back"/>
<EditText
android:id="@+id/txtPhoneNo"
android:layout_width="0dp"
android:layout_height="40dp"
android:background="@drawable/shape"
android:inputType="phone"
android:layout_weight="8"
android:hint="To"
android:padding="5dp"/>
<ImageView
android:id="@+id/idcont"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:src="@drawable/contact"/>
</LinearLayout>
<LinearLayout
android:id="@+id/idLn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<EditText
android:id="@+id/txtMessage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="9"
android:inputType="textMultiLine"
android:lines="5"
android:maxLength="160"
android:gravity="top"
android:background="@drawable/shape"
android:scrollHorizontally="false"
android:scrollbars="vertical"
android:hint="Text message"
android:padding="5dp"/>
<ImageView
android:layout_below="@+id/txtMessage"
android:id="@+id/btnSendSMS"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Send SMS"
android:layout_marginTop="10dp"
android:layout_gravity="center_vertical"
android:src="@drawable/sent"/>
</LinearLayout>

</RelativeLayout>





Layout looks like the screenshot 


Style mentioned in send.xml as android:background="@drawable/shape"  
In drawable folder create shape.xml with following details
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff" />
<stroke android:width="1dip" android:color="#ff9900" />
</shape>

STEP:4

Create the SendActivity.java


public class SendActivity extends Activity {
    ImageView imgSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;
    ImageView imgBack;
    ImageView imgContact;
    private static final int PICK_CONTACT=1;
    @Override    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send);
        imgSendSMS = (ImageView) findViewById(R.id.btnSendSMS);
        imgBack = (ImageView) findViewById(R.id.idback);
        imgContact = (ImageView) findViewById(R.id.idcont);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);
        imgSendSMS.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 back screen        
imgBack.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent myIntent = new Intent(SendActivity.this, MainActivity.class);
                SendActivity.this.startActivity(myIntent);
            }
        });
//How to select the mobile number from contact(detailed in next article)
        imgContact.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent(Intent.ACTION_PICK, 
ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, PICK_CONTACT);
            }
        });

    }

    //select contact trough intent    
@Override    
public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);
        Log.e("COMING","ONE");
        switch (reqCode) {
            case (PICK_CONTACT) :
              if (resultCode == Activity.RESULT_OK) {
              Log.e("COMING","TWO");
              Uri contactData = data.getData();
              Cursor c =  getContentResolver().query
(contactData, null, null, null, null);
              if (c.moveToFirst()) {
              String name = c.getString(c.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
              String contactId = c.getString(c.getColumnIndex
(ContactsContract.Contacts._ID));
              String hasNumber = c.getString(c.getColumnIndex
(ContactsContract.Contacts.HAS_PHONE_NUMBER));
              String num = "";
                if (Integer.valueOf(hasNumber) == 1) {
                    Cursor numbers = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " 
+ contactId, null, null);
                        while (numbers.moveToNext()) {
                            num = numbers.getString(numbers.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            txtPhoneNo.setText(""+num);
                            }
                        }
                    }
                }
                break;
        }
    }

    //—sends a SMS message to another device—    
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);

//        Intent myIntent = new Intent(SendActivity.this, MainActivity.class);
//        SendActivity.this.startActivity(myIntent);    }
}

Receiving SMS Messages

Besides programmatically sending SMS messages, you can also intercept incoming SMS messages using a BroadcastReceiver object.

STEP-1

To see how to receive SMS messages from within your Android application, in theAndroidManifest.xml file add the element so that incoming SMS messages can be intercepted by the ReceiveActivity class

<receiver android:name=".ReceiveActivity" android:exported="true" >
    <intent-filter android:priority="999" >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>


Add permission 

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

STEP-2

Create ReceiveActivity.java with extends BroadcastReceiver
public class ReceiveActivity extends BroadcastReceiver {
    public static final String SMS_BUNDLE = "pdus";

    public void onReceive(Context context, Intent intent) {
        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null) {
            Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
            String smsMessageStr = "";
            for (int i = 0; i < sms.length; ++i) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

                String smsBody = smsMessage.getMessageBody().toString();
                String address = smsMessage.getOriginatingAddress();

                smsMessageStr += "SMS From: " + address + "\n";
                smsMessageStr += smsBody + "\n";
            }
            Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

            //this will update the UI with message       
MainActivity inst = MainActivity.instance();
       inst.updateList(smsMessageStr);
        }
    }
}

STEP-3
activity_main.xml is automatically created when select Basic
Activity when start android studio application
In content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:background="@color/bgHead"  
   android:paddingBottom="@dimen/activity_vertical_margin" 
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   app:layout_behavior="@string/appbar_scrolling_view_behavior"  
   tools:context="com.example.mrbrown.mrbrown_sms.MainActivity"  
   tools:showIn="@layout/activity_main">
 <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="wrap_content"          
   android:layout_height="wrap_content"          
   android:textAppearance="?android:attr/textAppearanceMedium"          
   android:text="SMS Inbox"          
   android:textStyle="bold"          
   android:id="@+id/textView"          
   android:layout_gravity="center_horizontal" />
 <ListView
   android:id="@+id/SMSList"          
   android:layout_height="wrap_content"          
   android:layout_width="match_parent"          
   android:layout_margin="5dp"         
   android:background="#ffe6ee"/>
 </LinearLayout>
</RelativeLayout>

STEP-4

In MainActivity.java with extend Activity and implements OnItemClickListener

public class MainActivity extends Activity implements 
 
AdapterView.OnItemClickListener {
 
    private static MainActivity inst;
    ArrayList<String> smsMessagesList = new ArrayList<String>();
    ListView smsListView;
    ArrayAdapter arrayAdapter;
 
    public static MainActivity instance() {
        return inst;
    }
    @Override    public void onStart() {
        super.onStart();
        inst = this;
    }
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        smsListView = (ListView) findViewById(R.id.SMSList);
        arrayAdapter = new ArrayAdapter<String>

(this, android.R.layout.simple_list_item_1, smsMessagesList);
        smsListView.setAdapter(arrayAdapter);
        smsListView.setOnItemClickListener(this);
 
        refreshSmsInbox();
 
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        assert fab != null;
        fab.setOnClickListener(new View.OnClickListener() {
            @Override            
 
public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)//                        .setAction("Action", null).show();                Intent myIntent = new Intent(MainActivity.this, SendActivity.class);
   MainActivity.this.startActivity(myIntent);
            }
        });
    }
    public void refreshSmsInbox() {
        ContentResolver contentResolver = getContentResolver();
        Cursor smsInboxCursor = contentResolver.query
 
(Uri.parse("content://sms/inbox"), null, null, null, null);
        int indexBody = smsInboxCursor.getColumnIndex("body");
        int indexAddress = smsInboxCursor.getColumnIndex("address");
        if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
        arrayAdapter.clear();
        do {
            String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
                    "\n" + smsInboxCursor.getString(indexBody) + "\n";
            arrayAdapter.add(str);
        } while (smsInboxCursor.moveToNext());
    }
 
    public void updateList(final String smsMessage) {
        arrayAdapter.insert(smsMessage, 0);
        arrayAdapter.notifyDataSetChanged();
    }
 
    public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
        try {
            String[] smsMessages = smsMessagesList.get(pos).split("\n");
            String address = smsMessages[0];
            String smsMessage = "";
            for (int i = 1; i < smsMessages.length; ++i) {
                smsMessage += smsMessages[i];
            }
 
            String smsMessageStr = address + "\n";
            smsMessageStr += smsMessage;
            Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Complete Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mrbrown.mrbrown_sms">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
<action
android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</activity>
<receiver
android:name=".ReceiveActivity" android:exported="true"
> 
<intent-filter android:priority="999" >
<action
android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity
android:name=".SendActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
<uses-permission
android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission
android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"
/>
<uses-permission
android:name="android.permission.READ_CONTACTS"/>
</manifest>
Output screenshots

__________________________________________________

Source Code for this application MrBrownSMS.rar
Happy Coding...

Comments


  1. Get ready SMS PHP API or Bulk SMS API PHP Gateway Integration Source Code/Script to Integrate into your website, software or web application. MsgClub PHP APIs helps to send verification code or OTP, Transactional & Promotional SMS from your PHP based application automatically.
    bulk SMS API

    ReplyDelete

Post a Comment

Popular posts from this blog

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ______________________________________...

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t...

Bluetooth Chat Application - Android Tutorial

In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section ...