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.
  1. Android Programming - Day One
  2. Android Programming - Day Two
  3. How To Display A Dialog Windows In Android
  4. How To Display A Progress Dialog Window In Android
  5. Intent In Android
  6. Return Data Using Intent Object In Android Applications
  7. Passing Data Using An Intent Object In Android Applications
  8. Fragments In Android Applications
  9. Adding Fragments Dynamically In Android Application
  10. Fragment Life Cycle In Android Application
  11. Interaction Between Two Fragments
  12. Calling In-Built Functions in Android Application
  13. Intent Object and Intent Filters in Android Application

Introduction

You have already aware of 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. Users may easily miss 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 the NotificationManager class to display a persistent message at the top of the device which is known as a status bar.
Code
Create a new project named ShowNotification.
displaying-notifications-in-android-applications
Create a blank activity called MainActivity.
displaying-notifications-in-android-applications
Add a new blank activity.
displaying-notifications-in-android-applications
And name it DisplayNotification.
displaying-notifications-in-android-applications
Add code in this class

  1. package com.example.administrator.shownotification;
  2. import android.app.NotificationManager;
  3. import android.support.v7.app.ActionBarActivity;
  4. import android.os.Bundle;
  5. import android.view.Menu;
  6. import android.view.MenuItem;
  7. public class DisplayNotification extends ActionBarActivity {
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.activity_display_notification);
  12. //Look up the notification manager service
  13. NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  14. // Cancel the notification that we started
  15. notificationManager.cancel(getIntent().getExtras().getInt("NotificationID"));
  16. }
  17. @Override
  18. public boolean onCreateOptionsMenu(Menu menu) {
  19. // Inflate the menu; this adds items to the action bar if it is present.
  20. getMenuInflater().inflate(R.menu.menu_display_notification, menu);
  21. return true;
  22. }
  23. @Override
  24. public boolean onOptionsItemSelected(MenuItem item) {
  25. // Handle action bar item clicks here. The action bar will
  26. // automatically handle clicks on the Home/Up button, so long
  27. // as you specify a parent activity in AndroidManifest.xml.
  28. int id = item.getItemId();
  29. //noinspection SimplifiableIfStatement
  30. if (id == R.id.action_settings) {
  31. return true;
  32. }
  33. return super.onOptionsItemSelected(item);
  34. }
  35. }
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. <uses-sdk android:minSdkVersion="20"/>
  8. <uses-permission android:name="android.permission.VIBRATE"/>
  9. <application
  10. android:allowBackup="true"
  11. android:icon="@mipmap/ic_launcher"
  12. android:label="@string/app_name"
  13. android:theme="@style/AppTheme" >
  14. <activity
  15. android:name=".MainActivity"
  16. android:label="@string/app_name" >
  17. <intent-filter>
  18. <action android:name="android.intent.action.MAIN" />
  19. <category android:name="android.intent.category.LAUNCHER" />
  20. </intent-filter>
  21. </activity>
  22. <activity
  23. android:name=".DisplayNotification"
  24. android:label="@string/title_activity_display_notification" >
  25. <intent-filter>
  26. <action android:name="android.intent.action.MAIN"/>
  27. <category android:name="android.intent.category.DEFAULT"/>
  28. </intent-filter>
  29. </activity>
  30. </application>
  31. </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. <Button android:id="@+id/buttondisplaynotification"
  7. android:layout_width="fill_parent"
  8. android:layout_height="fill_parent"
  9. android:text="Show Notification"
  10. android:onClick="onClickShowNotification"
  11. />
  12. </LinearLayout>
Implemented the onClickShowNotification() in the MainActivity.java class and it looks like this
  1. package com.example.administrator.shownotification;
  2. import android.app.Notification;
  3. import android.app.NotificationManager;
  4. import android.app.PendingIntent;
  5. import android.app.TaskStackBuilder;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.support.v4.app.NotificationCompat;
  9. import android.support.v7.app.ActionBarActivity;
  10. import android.os.Bundle;
  11. import android.view.Menu;
  12. import android.view.MenuItem;
  13. import android.view.View;
  14. public class MainActivity extends ActionBarActivity {
  15. int notificationId=10;
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. }
  21. public void onClickShowNotification(View view)
  22. {
  23. displayNotification();
  24. }
  25. protected void displayNotification(){
  26. NotificationCompat.Builder mBuilder =
  27. new NotificationCompat.Builder(this)
  28. .setSmallIcon(R.drawable.ic_launcher)
  29. .setContentTitle("System Alarm")
  30. .setContentText("Meeting with client at 4 PM!!");
  31. // Creates an explicit intent for an Activity
  32. Intent resultIntent = new Intent(this, DisplayNotification.class);
  33. // The stack builder object will contain an artificial back stack for the started Activity.
  34. // This ensures that navigating backward from the Activity leads out of
  35. // the application to the Home screen.
  36. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  37. // Adds the back stack for the Intent except Intent itself
  38. stackBuilder.addParentStack(DisplayNotification.class);
  39. // Adds the Intent that starts the Activity to the top of the stack
  40. stackBuilder.addNextIntent(resultIntent);
  41. PendingIntent resultPendingIntent =
  42. stackBuilder.getPendingIntent(
  43. 0,
  44. PendingIntent.FLAG_UPDATE_CURRENT
  45. );
  46. mBuilder.setContentIntent(resultPendingIntent);
  47. NotificationManager mNotificationManager =
  48. (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  49. // notificationId allows to update the notification later on.
  50. mNotificationManager.notify(notificationId, mBuilder.build());
  51. }
  52. @Override
  53. public boolean onCreateOptionsMenu(Menu menu) {
  54. // Inflate the menu; this adds items to the action bar if it is present.
  55. getMenuInflater().inflate(R.menu.menu_main, menu);
  56. return true;
  57. }
  58. @Override
  59. public boolean onOptionsItemSelected(MenuItem item) {
  60. // Handle action bar item clicks here. The action bar will
  61. // automatically handle clicks on the Home/Up button, so long
  62. // as you specify a parent activity in AndroidManifest.xml.
  63. int id = item.getItemId();
  64. //noinspection SimplifiableIfStatement
  65. if (id == R.id.action_settings) {
  66. return true;
  67. }
  68. return super.onOptionsItemSelected(item);
  69. }
  70. }
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. // The stack builder object will contain an artificial back stack for the started Activity.
  3. // This ensures that navigating backward from the Activity leads out of
  4. // the application to the Home screen.
  5. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  6. // Adds the back stack for the Intent except Intent itself
  7. stackBuilder.addParentStack(DisplayNotification.class);
  8. // Adds the Intent that starts the Activity to the top of the stack
  9. stackBuilder.addNextIntent(resultIntent);
  10. PendingIntent resultPendingIntent =
  11. stackBuilder.getPendingIntent(
  12. 0,
  13. PendingIntent.FLAG_UPDATE_CURRENT
  14. );
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.
displaying-notifications-in-android-applications
Touch or click the text Show Notification display in the center of the above screen.
displaying-notifications-in-android-applications
It displays the notification on the UI screen.

Conclusion

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