Demonstrating the system service Notification Service and NotificationManager by sending SMS using SMSManager in Android

August 23, 2012
By

In the article titled “Sending SMS directly from an application using SmsManager in Android“, we created an Android application which can send SMS text messages using SmsManager.

In this article we will create an extension to that application which can create notification messages when messages are successfully send or delivered.

An instance of NotificationManager is obtained from the system service called “NOTIFICATION_SERVICE”. Since the constructor and some other vital functions of the class android.app.Notification is deprecated, we will make use the class android.support.v4.app.NotificationCompat.Builder which is supported from Android API level 5 onwards using Android backward compatibility support library.

This application is developed in Eclipse Classic ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 )


1. Create a new Android application project titled “SmsSendNotification”

New Android Application Project

Figure 1 : New Android Application Project


2. Design an application launcher icon

Design application launcher icon

Figure 2 : Design application launcher icon


3. Create a blank activity

Create a blank Activity

Figure 3 : Create a blank Activity


4. Enter MainActivity details

Enter MainActivity details

Figure 4 : Enter MainActivity details


5. Add Android’s Backward compatibility Support Library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project ( “DatePickerDialogDemo”)
  • Then from popup window, Click “Android Tools -> Add Support Library “

6. Update the file res/values/strings.xml


<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">SmsSendNotification</string>
    <string name="str_hnt_to">Enter Telephone Number</string>
    <string name="str_hnt_message">Enter Message</string>
    <string name="str_btn_send">Send Message</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">SmsSendNotification</string>
</resources>


7. Update the layout file for the MainActivity in the file res/layout/activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/et_number"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/str_hnt_to"
        android:inputType="number"
    />

    <EditText
        android:id="@+id/et_message"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/str_hnt_message"
        android:inputType="textMultiLine"
        android:minLines="6"
    />

    <Button
        android:id="@+id/btn_send"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/str_btn_send"
    />
</LinearLayout>


8. Create  the layout file for the notification activity in the file res/layout/notification.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_sms_sent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
</LinearLayout>


9. Create the notification activity in the file src/in/wptrafficanalyzer/smssendnotification/NotificationView.java

package in.wptrafficanalyzer.smssendnotification;

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

public class NotificationView extends Activity {
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification);

        TextView tv = (TextView) findViewById(R.id.tv_sms_sent);
        Bundle data = getIntent().getExtras();
        tv.setText(data.getString("number"));
    }
}


10. Create an activity class for handling SmsManager ‘s send and delivery events in the file src/in/wptrafficanalyzer/smssendnotification/SmsStatus.java


package in.wptrafficanalyzer.smssendnotification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

/**
* This activity will be invoked by SmsManager via Pending intents defined in MainActivity
*/
public class SmsStatus extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Getting bundle object attached to the intent */
        Bundle data = getIntent().getExtras();

        /** Getting the data "status" from the bundle object */
        int status = data.getInt("status");

        /** Getting the data "number" from the bundle object */
        String number = data.getString("number");

        String notificationTitle = "";
        String notificationContent  = "";
        String tickerMessage = "";

        if(status==MainActivity.SENT){    /** Detecting which intent invoked this execution of activity */
            Toast.makeText(getBaseContext(), "Message successfully Sent", Toast.LENGTH_SHORT).show();
            notificationTitle="Message Successfully Sent";
            notificationContent="Message is successfully sent to " + number ;
            tickerMessage = "Message Successfully sent";

        }else if(status==MainActivity.DELIVERED){    /** Detecting which intent invoked this execution of activity */
            Toast.makeText(getBaseContext(), "Message successfully Delivered", Toast.LENGTH_SHORT).show();
            notificationTitle="Message Successfully Delivered";
            notificationContent="Message is successfully delivered to " + number ;
            tickerMessage = "Message Successfully delivered";
        }

        /** Creating a notification intent which creates the activity NotificationView when the user clicks
        *  a notification from the notification list
        */
        Intent notificationIntent = new Intent(getApplicationContext(),NotificationView.class);
        notificationIntent.putExtra("number", notificationContent );

        /** This is needed to make this intent different from its previous intents */
        notificationIntent.setData(Uri.parse("tel:/"+ (int)System.currentTimeMillis()));

        /** Creating different tasks for each notification. See the flag Intent.FLAG_ACTIVITY_NEW_TASK */
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

        /** Getting the System service NotificationManager */
        NotificationManager nManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

        /** Configuring notification builder to create a notification */
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                    .setWhen(System.currentTimeMillis())
                    .setContentText(notificationContent)
                    .setContentTitle(notificationTitle)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setAutoCancel(true)
                    .setTicker(tickerMessage)
                    .setContentIntent(pendingIntent);

        /** Creating a notification from the notification builder */
        Notification notification = notificationBuilder.build();

        /** Sending the notification to system.
        * The first argument ensures that each notification is having a unique id
        * If two notifications share same notification id, then the last notification replaces the first notification
        * */
        nManager.notify((int)System.currentTimeMillis(), notification);

        /** Finishes the execution of this activity */
        finish();
    }
}


11. Updating the class MainActivity in the file src/in/wptrafficanalyzer/smssendnotification/MainActivity.java


package in.wptrafficanalyzer.smssendnotification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

    public static final int SENT = 0;
    public static final int DELIVERED = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                /** Getting reference to et_number of main.xml */
                EditText etNumber = (EditText) findViewById(R.id.et_number);

                /** Getting reference to et_message of main.xml */
                EditText etMessage = (EditText) findViewById(R.id.et_message);

                String number = etNumber.getText().toString();
                String message = etMessage.getText().toString();

                /** Creating an intent, corresponding to sent delivery report */
                /** This intent will call the activity SmsStatus */
                Intent sentIntent = new Intent("in.wptrafficanalyzer.activity.status.sent");

                /** Sms is sent to this number */
                sentIntent.putExtra("number", number);

                /** Setting status data on the intent */
                sentIntent.putExtra("status", SENT);

                /** Creating an intent, corresponding to delivered delivery report */
                /** This intent will call the activity SmsStatus */
                Intent deliveredIntent = new Intent("in.wptrafficanalyzer.activity.status.delivered");

                /** Sms is sent to this number */
                deliveredIntent.putExtra("number", number);

                /** Setting status data on the intent */
                deliveredIntent.putExtra("status", DELIVERED);

                /** Creating a pending intent which will be invoked by SmsManager when an sms message is successfully sent */
                PendingIntent piSent = PendingIntent.getActivity(getBaseContext(), 0, sentIntent, PendingIntent.FLAG_ONE_SHOT);

                /** Creating a pending intent which will be invoked by SmsManager when an sms message is successfully delivered */
                PendingIntent piDelivered = PendingIntent.getActivity(getBaseContext(), 0, deliveredIntent, PendingIntent.FLAG_ONE_SHOT);

                /** Getting an instance of SmsManager to sent sms message from the application*/
                SmsManager smsManager = SmsManager.getDefault();

                /** Sending the Sms message to the intended party */
                smsManager.sendTextMessage(number, null, message, piSent, piDelivered);

            }
        };
        /** Getting reference to btn_send of main.xml */
        Button btnSend = (Button) findViewById(R.id.btn_send);

        /** Setting a click event listener for the button */
        btnSend.setOnClickListener(listener);
    }
}


12. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.smssendnotification"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="5"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".NotificationView"
            android:label="@string/app_name" >

            <intent-filter >
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>

        <activity
            android:name=".SmsStatus"
            android:label="@string/app_name" >
            <intent-filter >
                <action android:name="in.wptrafficanalyzer.activity.status.sent"/>
                <action android:name="in.wptrafficanalyzer.activity.status.delivered"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

    </application>
</manifest>


13. Screenshots of the application in execution

Sending Sms Text Message

Figure 5 : Sending Sms Text Message

Expanded Notifications List

Figure 6 : Expanded Notifications List

A notification when opened

Figure 7 : A notification when opened


14. Download


15. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner