Displaying Notifications In Android Applications

Overview

Notifications have a very important role in any mobile development application. It is a faster way of communication to provide information to the user. Today, we get notifications for almost every time when a user does any kind of transaction, either on social media apps or any financial/services related apps. Before starting a discussion on notifications, below are some useful links to start programming in Android applications from scratch.

Introduction

You have already aware with using the Toast class to display a message to the user. This class is a handy way to show user alerts, it is not persistent. It flashes on the screen for a few seconds and then disappears. User may easily miss the important information if they are not looking at the screen.

Messages are more important, so we need to use a more persistent method. For this, you can use NotificationManager class to display a persistent message at the top of the device which is known as status bar.

Code

Create a new project named ShowNotification.


Create a blank activity called MainActivity.


Add a new blank activity.

 

And name it DisplayNotification.

 

Add code in this class

  1. package com.example.administrator.shownotification;  
  2.   
  3. import android.app.NotificationManager;  
  4. import android.support.v7.app.ActionBarActivity;  
  5. import android.os.Bundle;  
  6. import android.view.Menu;  
  7. import android.view.MenuItem;  
  8.   
  9. public class DisplayNotification extends ActionBarActivity {  
  10.   
  11. @Override  
  12. protected void onCreate(Bundle savedInstanceState) {  
  13.     super.onCreate(savedInstanceState);  
  14.     setContentView(R.layout.activity_display_notification);  
  15.     //Look up the notification manager service  
  16.     NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);  
  17.     // Cancel the notification that we started  
  18.     notificationManager.cancel(getIntent().getExtras().getInt("NotificationID"));  
  19. }  
  20.   
  21. @Override  
  22. public boolean onCreateOptionsMenu(Menu menu) {  
  23. // Inflate the menu; this adds items to the action bar if it is present.  
  24. getMenuInflater().inflate(R.menu.menu_display_notification, menu);  
  25. return true;  
  26. }  
  27.   
  28. @Override  
  29. public boolean onOptionsItemSelected(MenuItem item) {  
  30. // Handle action bar item clicks here. The action bar will  
  31. // automatically handle clicks on the Home/Up button, so long  
  32. // as you specify a parent activity in AndroidManifest.xml.  
  33. int id = item.getItemId();  
  34.   
  35. //noinspection SimplifiableIfStatement  
  36. if (id == R.id.action_settings) {  
  37. return true;  
  38. }  
  39.   
  40. return super.onOptionsItemSelected(item);  
  41. }  
  42. }   

Add <intent-filter> and <uses-permisson> in the AndroidMenifest.xml file

  1. <?xml version="1.0" encoding="utf-8"?>  
  2.  <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.      package="com.example.administrator.shownotification"  
  4.      android:versionCode="1"  
  5.      android:versionName="1.0"  
  6.      >  
  7.    
  8.      <uses-sdk android:minSdkVersion="20"/>  
  9.      <uses-permission android:name="android.permission.VIBRATE"/>  
  10.      <application  
  11.          android:allowBackup="true"  
  12.          android:icon="@mipmap/ic_launcher"  
  13.          android:label="@string/app_name"  
  14.          android:theme="@style/AppTheme" >  
  15.          <activity  
  16.              android:name=".MainActivity"  
  17.              android:label="@string/app_name" >  
  18.              <intent-filter>  
  19.                  <action android:name="android.intent.action.MAIN" />  
  20.    
  21.                  <category android:name="android.intent.category.LAUNCHER" />  
  22.              </intent-filter>  
  23.          </activity>  
  24.          <activity  
  25.              android:name=".DisplayNotification"  
  26.              android:label="@string/title_activity_display_notification" >  
  27.              <intent-filter>  
  28.                  <action android:name="android.intent.action.MAIN"/>  
  29.                      <category android:name="android.intent.category.DEFAULT"/>  
  30.              </intent-filter>  
  31.          </activity>  
  32.      </application>  
  33.    
  34.  </manifest>  

Activity_main.xml file looks like this

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.      xmlns:tools="http://schemas.android.com/tools"  
  3.      android:orientation="vertical"  
  4.      android:layout_width="fill_parent"  
  5.      android:layout_height="fill_parent"  tools:context=".MainActivity">  
  6.    
  7.      <Button android:id="@+id/buttondisplaynotification"  
  8.          android:layout_width="fill_parent"  
  9.          android:layout_height="fill_parent"  
  10.          android:text="Show Notification"  
  11.          android:onClick="onClickShowNotification"  
  12.          />  
  13.    
  14.    
  15.  </LinearLayout>  
Implemented the onClickShowNotification() in the MainActivity.java class and it looks like this
  1. package com.example.administrator.shownotification;  
  2.    
  3.  import android.app.Notification;  
  4.  import android.app.NotificationManager;  
  5.  import android.app.PendingIntent;  
  6.  import android.app.TaskStackBuilder;  
  7.  import android.content.Context;  
  8.  import android.content.Intent;  
  9.  import android.support.v4.app.NotificationCompat;  
  10.  import android.support.v7.app.ActionBarActivity;  
  11.  import android.os.Bundle;  
  12.  import android.view.Menu;  
  13.  import android.view.MenuItem;  
  14.  import android.view.View;  
  15.    
  16.  public class MainActivity extends ActionBarActivity {  
  17.      int notificationId=10;  
  18.      @Override  
  19.      protected void onCreate(Bundle savedInstanceState) {  
  20.          super.onCreate(savedInstanceState);  
  21.          setContentView(R.layout.activity_main);  
  22.      }  
  23.      public void onClickShowNotification(View view)  
  24.      {  
  25.          displayNotification();  
  26.      }  
  27.      protected void displayNotification(){  
  28.    
  29.          NotificationCompat.Builder mBuilder =  
  30.                  new NotificationCompat.Builder(this)  
  31.                          .setSmallIcon(R.drawable.ic_launcher)  
  32.                          .setContentTitle("System Alarm")  
  33.                          .setContentText("Meeting with client at 4 PM!!");  
  34.   
  35.          // Creates an explicit intent for an Activity  
  36.          Intent resultIntent = new Intent(this, DisplayNotification.class);  
  37.    
  38.          // The stack builder object will contain an artificial back stack for the started Activity.  
  39.          // This ensures that navigating backward from the Activity leads out of  
  40.          // the application to the Home screen.  
  41.          TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);  
  42.          // Adds the back stack for the Intent except Intent itself  
  43.          stackBuilder.addParentStack(DisplayNotification.class);  
  44.          // Adds the Intent that starts the Activity to the top of the stack  
  45.          stackBuilder.addNextIntent(resultIntent);  
  46.          PendingIntent resultPendingIntent =  
  47.                  stackBuilder.getPendingIntent(  
  48.                          0,  
  49.                          PendingIntent.FLAG_UPDATE_CURRENT  
  50.                  );  
  51.          mBuilder.setContentIntent(resultPendingIntent);  
  52.          NotificationManager mNotificationManager =  
  53.                  (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
  54.          // notificationId allows to update the notification later on.  
  55.          mNotificationManager.notify(notificationId, mBuilder.build());  
  56.    
  57.      }  
  58.    
  59.      @Override  
  60.      public boolean onCreateOptionsMenu(Menu menu) {  
  61.          // Inflate the menu; this adds items to the action bar if it is present.  
  62.          getMenuInflater().inflate(R.menu.menu_main, menu);  
  63.          return true;  
  64.      }  
  65.    
  66.      @Override  
  67.      public boolean onOptionsItemSelected(MenuItem item) {  
  68.          // Handle action bar item clicks here. The action bar will  
  69.          // automatically handle clicks on the Home/Up button, so long  
  70.          // as you specify a parent activity in AndroidManifest.xml.  
  71.          int id = item.getItemId();  
  72.    
  73.          //noinspection SimplifiableIfStatement  
  74.          if (id == R.id.action_settings) {  
  75.              return true;  
  76.          }  
  77.    
  78.          return super.onOptionsItemSelected(item);  
  79.      }  
  80.  }  
Explanation

Created an object of class Builder which is inherited by NotificationCompat class. Set the title, icon and text to the object of the Builder class. Then define the notification’s action by using PendingIntent. The action itself is defined by a PendingIntent and Intent that starts and Activity in the application.
  1. Intent resultIntent = new Intent(this, DisplayNotification.class);  
  2.    
  3.  // The stack builder object will contain an artificial back stack for the started Activity.  
  4.  // This ensures that navigating backward from the Activity leads out of  
  5.  // the application to the Home screen.  
  6. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);  
  7.  // Adds the back stack for the Intent except Intent itself  
  8.  stackBuilder.addParentStack(DisplayNotification.class);  
  9.  // Adds the Intent that starts the Activity to the top of the stack  
  10.  stackBuilder.addNextIntent(resultIntent);  
  11.  PendingIntent resultPendingIntent =  
  12.          stackBuilder.getPendingIntent(  
  13.                  0,  
  14.                  PendingIntent.FLAG_UPDATE_CURRENT  
  15.          );  

To associate the PendingIntent created in the last step with a gesture, call the appropriate method of NotificationCompat.Builder. To start an activity when the user clicks the notification text in the notification drawer, add the PendingIntent by calling setContentIntent().

  1. mBuilder.setContentIntent(resultPendingIntent);  

At last, time to issue the notification. For this, get an instance of NotificationManager class. Use the notify() method. When you call notify(), specify a nofiticationid. You can use this ID to update notification later on. Call build(), which returns a Notification object containing your specifications.

  1. NotificationManager mNotificationManager =  
  2.          (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
  3.  // notificationId allows you to update the notification later on.  
  4.  mNotificationManager.notify(notificationId, mBuilder.build());  

Result

Run the application by pressing the button Shift + F10.


Touch or click the text Show Notification display in the center of the above screen


It displays the notification on the UI screen

Conclusion

In this article, I explained about displaying notifications using the concept of stack which means that all notifications are in the in queue. In the next article, I will explain about user interface in Android applications. If you have any questions or comments, post me a message in C# Corner comments section.

Up Next
    Ebook Download
    View all
    Learn
    View all