Tuesday, March 6, 2018

Creating Notification in Android

Notifications
A notification is an short alert  message paved in the notification panel in Android device, for ex when a SMS is received on device you see a new SMS alert in the notification panel



Using notification you can inform or alerts user about some event.


Elements of Notification
1: Content Title: title of the notification.
2: Content Text: detail of notification.
3: Icon : Icon for the notification.








Creating  Notifications

Notifications are created using NotificationCompat.Builder and NotificationManager class.
NotificationCompat.Builder class is used to build the notification element and NotificationManager class is used to show the notification.
Building notification
NotificationCompat.Builder mBuilder =
                                        new NotificationCompat.Builder(context)
                                        .setSmallIcon(R.drawable.icon)
                                        .setContentTitle("Notification Title”)
                                        .setContentText(“Notification detail text”);

Showing notification
// create NotificationMAnager object
NotificationManager mNotificationManager =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId=1;
// notify using NotificationManger object
mNotificationManager.notify(notificationId, mBuilder.build());

Cancelling the notification
You need to cancel a shown notification when user has seen and clicked over it after dragging the notification panel.
to cancel the displayed notification
mNotificationManager.cancel(notificationId);

Demo Application : “Showing new SMS Notification”


What we will do : we will create a SMSReceiver class which extends BroadcastReceiver class. We register this class in manifest file as a receiver for “SMS_RECEIVED “ action. The onReceive() method of SMSReceiver class will execute when a new SMS is received on device.
In onReceive() method we extract the SMS body, and SMS Sender number from the received message. We create a notification and show that a new SMS received.
Note : Do not forget the to declare the “android.permission.RECEIVE_SMS” permission and SMSReceiver in manifest file. “android.permission.RECEIVE_SMS”  permission is required to receive SMS.



AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.notification"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
   
    <!-- Permission to Receive SMS  -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
       
        <!--  register the SMSReceiver -->
        <receiver android:name=".SmsReceiver">
            <intent-filter>
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>





SMSReceiver.java

public class SMSReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();       
        SmsMessage[] msgs = null;
        String SMSBody = "";           
        if (bundle != null)
        {
            //---retrieve the SMS message received---
           Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];           
            for (int i=0; i<msgs.length; i++)

            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);               
                SMSBody += msgs[i].getMessageBody().toString();
            }

          // Get the Sender Phone Number
          String senderPhoneNumber=msgs[0].getOriginatingAddress ();
         
        //---display the new SMS message in toast---
          Toast.makeText(context, "SMS Revived from: "+senderPhoneNumber, Toast.LENGTH_SHORT).show();
         
        /* create the notification
         * set icon, title and text
         */
          NotificationCompat.Builder mBuilder =
                      new NotificationCompat.Builder(context)
                      .setSmallIcon(R.drawable.sms)
                      .setContentTitle("New SMS Recevied from: "+senderPhoneNumber)
                      .setContentText(SMSBody);
             

        // create NotificationMAnager object
       NotificationManager mNotificationManager =
                  (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
              int notificationId=1;
              // notify using NotificationManger object
              mNotificationManager.notify(notificationId, mBuilder.build());
             

       }                        
    }
}

No comments:

Post a Comment