Thursday, 5 September 2013

Before Sending Message

Send and track SMS

After Sending Message

Send and track SMS

Create new Android Project
Project Name: TextMessage
Build Target: Android 2.3.3   //or greater than that
Application Name: TextMessage
Package Name: com.shaikhhamadali.blogspot.textmessage
Create layout file: activity_messege_sender
Min SDK: 10 // or greater than that

  1. create main layout:
  • Two Edit Text (receiver number and Message)
  • one Button (send message)

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MessageSender" >

    <!-- Reciever Number edit text  -->
    <EditText
        android:id="@+id/eTReceiverNo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:hint="@string/enterReceiverNumber"
        android:ems="10"
        android:inputType="number" >
        <requestFocus />
    </EditText>
    
    <!-- Message multiline edit text  -->
    <EditText
        android:id="@+id/eTMessage"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_marginTop="60dp"
        android:ems="10"
        android:hint="@string/enterMessageHere"
        android:gravity="top"
        android:inputType="textMultiLine" />
 
 <!-- Send message Edit text -->
    <Button
        android:id="@+id/btnSend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"
        android:text="@string/send" />
</RelativeLayout>

2. code of string:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">TextMessage</string>
    <string name="action_settings">Settings</string>
    <string name="enterMessageHere">enter message here</string>
    <string name="enterReceiverNumber">enter receiver number</string>
    <string name="send">Send</string>

</resources>

3. code of manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shaikhhamadali.blogspot.textmessage"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        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.shaikhhamadali.blogspot.textmessage.MessageSender"
            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>


6code of main activity:

package com.shaikhhamadali.blogspot.textmessage;

import java.util.Set;

import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MessageSender extends Activity {
 private final static String TAG = "MessageSenderActivity";
 private final static String INTENT_ACTION_SENT = "com.shaikhhamadali.blogspot.textmessage.INTENT_ACTION_SENT";
 private final static String INTENT_ACTION_DELIVERY = "com.shaikhhamadali.blogspot.textmessage.INTENT_ACTION_DELIVERY";
 private final static int REQUEST_CODE_ACTION_SENT = 1;
 private static final int REQUEST_CODE_ACTION_DELIVERY = 2;
 private BroadcastReceiver smsSentDeliveredReceiver;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_message_sender);
  //Receiver edit text
  final EditText eTReceiverNumebr = (EditText) findViewById(R.id.eTReceiverNo);
  //Sender edit text
  final EditText eTMessage = (EditText) findViewById(R.id.eTMessage);
  //Send Message Button
  Button btnSend = (Button) findViewById(R.id.btnSend);
  btnSend.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    //get receiver number
    String number = eTReceiverNumebr.getText().toString();
    //get message to send
    String message = eTMessage.getText().toString();
    //call send sms message method to send the sms
    sendSMS(number, message);
   }
  });
  //initialize broadcast receiver for message delivery
  initializeReceivers();

 }

 private void sendSMS(String number, String message) {
  /*create intent instance and pass INTENT_ACTION_SENT
   * INTENT_ACTION_SENT is used to send an sms on GSM 
   * */ 
  Intent sentIntent = new Intent(INTENT_ACTION_SENT);
  /*create pendingintent instance and pass this as context instance,REQUEST_CODE_ACTION_SENT and FLAG_UPDATE_CURRENT 
   * REQUEST_CODE_ACTION_SENT=1 defined at top
   * FLAG_UPDATE_CURRENT: Flag for use with getActivity(Context, int, Intent, int),
   *  getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int):
   *  if the described PendingIntent already exists, then keep it but its replace
   *  its extra data with what is in this new Intent. This can be used if you are
   *  creating intents where only the extras change, and don't care that any 
   *  entities that received your previous PendingIntent will be able to launch
   *  it with your new extras even if they are not explicitly given to it. 
   * */
  PendingIntent pendingSentIntent = PendingIntent.getBroadcast(this,
    REQUEST_CODE_ACTION_SENT, sentIntent,
    PendingIntent.FLAG_UPDATE_CURRENT);
  /*create intent instance and pass INTENT_ACTION_DELIVERY
   * INTENT_ACTION_DELIVERY is used to receive an sms delivery on GSM 
   * */ 
  Intent deliveryIntent = new Intent(INTENT_ACTION_DELIVERY);
  /*create pendingintent instance and pass this as context instance,REQUEST_CODE_ACTION_DELIVERY and FLAG_UPDATE_CURRENT 
   * REQUEST_CODE_ACTION_DELIVERY=2 defined at top
   * FLAG_UPDATE_CURRENT:Flag for use with getActivity(Context, int, Intent, int),
   *  getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int):
   *  if the described PendingIntent already exists, then keep it but its replace its 
   *  extra data with what is in this new Intent. This can be used if you are creating
   *  intents where only the extras change, and don't care that any entities that received
   *  your previous PendingIntent will be able to launch it with your new extras even if 
   *  they are not explicitly given to it. 
   * */
  PendingIntent pendingDeliveryIntent = PendingIntent.getBroadcast(this,
    REQUEST_CODE_ACTION_DELIVERY, deliveryIntent,
    PendingIntent.FLAG_UPDATE_CURRENT);
  //Create instance of SmsManager and get the default instance of the Sms manager
  SmsManager smsManager = SmsManager.getDefault();

  /* Second parameter is the service center number. Use null if you want
   *to use the default number */
  smsManager.sendTextMessage(number, null, message, pendingSentIntent,
    pendingDeliveryIntent);
 }
 @Override
 protected void onPause() {
  super.onPause();
  unregisterReceiver(smsSentDeliveredReceiver);
 }
 @Override
 protected void onResume() {
  super.onResume();
  //Create instance of intent filter and add actions we defined
  IntentFilter filter = new IntentFilter(INTENT_ACTION_SENT);
  filter.addAction(INTENT_ACTION_DELIVERY);
  //register receiver for our defined actions
  registerReceiver(smsSentDeliveredReceiver, filter);
 }
 private void initializeReceivers() {
  //sent sms delivery receiver
  smsSentDeliveredReceiver = new BroadcastReceiver() {

   @Override
   public void onReceive(Context context, Intent intent) {
    //call process broadcasts method
    processBroadcasts(intent);
   }
  };
 }
 private void processBroadcasts(Intent intent) {
  //get action
  String action = intent.getAction();
  //log as info in logcat the received action
  Log.i(TAG, "Received: " + action);

  if (action.equals(INTENT_ACTION_SENT)) {
   Bundle bundle = intent.getExtras();
   // can check for error messages
   //log as info in logcat that message sent    
   Log.i(TAG, "Message: Sent");
   //show toast that message sent
   Toast.makeText(this, "Message sent", Toast.LENGTH_LONG).show();
  } else if (action.equals(INTENT_ACTION_DELIVERY)) {
   
   Bundle bundle = intent.getExtras();
   Set<String> keys = bundle.keySet();
   // can check for error messages
   //log as info in logcat that message Delivered
   Log.i(TAG, "Message: Delivered");
   //show toast that message Delivered
   Toast.makeText(this, "Message delivered", Toast.LENGTH_LONG).show();
  }
 }
}

7. note that:
8. conclusion:
  • Some information about SmsManager,Broad Cast Receivers and permissions.
  • Know how to send an  sms.
  • Know how to get notification of sms delivered.
9. about the post:
  •  Coming posts could be Receive Message,types of Intent,types of Toast ets 
  •  The code seems to explain itself due to comments, and is very easy to understand.
  •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
  •  Hope you enjoy it!

10. Source Code:
        you can download the source code here

Cheers,
Hamad Ali Shaikh