Android Notification Example With NotificationCompat

By | February 10, 2014
Android Notification Allows your application to put notification in the titlebar , and the user can click on this notfication to move another activity .
 
Here In this tutorial , we will see an example of creating and closing notification with three buttons.
Android Notification

 1. Creating Notification

     To Create a notification we use of NotificationCompat.Builder  Object .
   
     NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(
    this)
    
    The Builder object as a set of  methods to define the property for the notification .
      
  1.      Icon : setSmallIcon(R.drawable.icon) .
  2.      Title :setContentTitle(“Title”) .
  3.      Text :setContentText(“Text”) .
  4.      Intent : setContentIntent(IntentOBJ) .
  5.      ActionButton :addAction(R.drawable.ic_launcher, “View”, IntentOBJ) .
  6.      AutoCancel :setAutoCancel(true) .

2.  Issuing Notification :

      To Issue Notification we use of NotificationManager object and call notify method on this object by passing Notification ID and Builder Object .
      
       NotificationManager notifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
       int notificationId = 01;
       notifyMgr.notify(notificationId, nBuilder.build());
 

  3.  Closing Notification :

       There are Two Ways of Closing Notification
     a) Close by ID .
        To close notfication by ID just call cancel method on NotificationManager object and pass ID as a  parameter to it
     b)  Close all Notification.
        To close all notification just call cancelAll method on NotificationManager object .
  

Lets See An Example

Project Detail

Project Name NotificationDemo
Package com.pavan.notificationdemo
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

1. XML Layout

file :- activity_main.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
    xmlns:android=”http://schemas.android.com/apk/res/android”
    android:layout_width=”fill_parent”
    android:layout_height=”fill_parent”
    android:orientation=”vertical”
    android:padding=”10dp” >

    <Button
        android:id=”@+id/Create_bt”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:text=”Create Notification” />

    <Button
        android:id=”@+id/CloseID_bt”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:text=”Close Notification by ID” />

    <Button
        android:id=”@+id/CloseAll_bt”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:text=”Close All” />

</LinearLayout>

file:- notify_activity.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:orientation=”vertical”
    android:padding=”20dp” >

    <TextView
        android:id=”@+id/textView1″
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:text=”In Notifcation Activity”
        android:textAppearance=”?android:attr/textAppearanceLarge” />

</LinearLayout>

2. Activities

 file:- MainActivity.java

package com.pavan.notificationdemo;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

 Button create_bt, closeID_bt, closeAll_bt;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // initialize
  create_bt = (Button) findViewById(R.id.Create_bt);
  closeID_bt = (Button) findViewById(R.id.CloseID_bt);
  closeAll_bt = (Button) findViewById(R.id.CloseAll_bt);

  // SetOnclickListener
  create_bt.setOnClickListener(this);
  closeID_bt.setOnClickListener(this);
  closeAll_bt.setOnClickListener(this);

 }

 @Override
 public void onClick(View v) {
 
  switch (v.getId()) {
  case R.id.Create_bt:
   CreateNotification();
   break;

  case R.id.CloseID_bt:
   CloseNotificationByID(01);
   break;

  case R.id.CloseAll_bt:
   CloseAllNotification();
   break;
  }

 }

 void CreateNotification() {
  // Create Intent for notification
  Intent intent = new Intent(this, NotifyReceiver.class);
  PendingIntent pi = PendingIntent.getActivity(this, 0, intent,
    PendingIntent.FLAG_UPDATE_CURRENT);

  // Defining notification
  NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(
    this).setSmallIcon(R.drawable.ic_launcher)
    .setContentTitle(“Subject”)
    .setContentText(“Here’s an mail from …”).setContentIntent(pi)
    .addAction(R.drawable.ic_launcher, “View”, pi);

  // Allows notification to be cancelled when user clicks it
  nBuilder.setAutoCancel(true);

  // Issuing notification

  int notificationId = 01;
  NotificationManager notifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

  notifyMgr.notify(notificationId, nBuilder.build());

 }

 void CloseNotificationByID(int notificationID) {
  if (Context.NOTIFICATION_SERVICE != null) {
   String NS = Context.NOTIFICATION_SERVICE;
   NotificationManager nMgr = (NotificationManager) getApplicationContext()
     .getSystemService(NS);
   nMgr.cancel(notificationID);
  }

 }

 void CloseAllNotification() {
  if (Context.NOTIFICATION_SERVICE != null) {
   NotificationManager nMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
   nMgr.cancelAll();
  }

 }
}

 file:- NotifyReceiver.java

package com.pavan.notificationdemo;
import android.app.Activity;
import android.os.Bundle;

public class NotifyReceiver extends Activity{

 @Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.notify_activity);
 }
}

3. AndroidManifest

 file:- AndroidManifest.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
    package=”com.pavan.notificationdemo”
    android:versionCode=”1″
    android:versionName=”1.0″ >

    <uses-sdk
        android:minSdkVersion=”8″
        android:targetSdkVersion=”17″ />

    <application
        android:allowBackup=”true”
        android:icon=”@drawable/ic_launcher”
        android:label=”@string/app_name”
        android:theme=”@style/AppTheme” >
        <activity
            android:name=”com.pavan.notificationdemo.MainActivity”
            android:label=”@string/app_name” >
            <intent-filter>
                <action android:name=”android.intent.action.MAIN” />

                <category android:name=”android.intent.category.LAUNCHER” />
            </intent-filter>
        </activity>
        <activity
          android:name=”com.pavan.notificationdemo.NotifyReceiver”
          android:label=”@string/app_name” >
        </activity>
    </application>
</manifest>

4. RUN

Android Notification Example

Android Notification Example

Android Notification Example

  • thank you for your appreciation
    stay tuned for more upcoming articles 🙂

  • Anonymous

    Hey Pavan,

    This is hari.. Kotini friend.. I was a part of your team when I worked in *****… He referred me to read this blog to learn android.. Your posts are very informative and easy to understand..
    Keep doing gud..

  • @Pavan once u understand notification means its shows now you are good in android.
    I think for Hari its helps lot to understand basic android .
    Keep good work ..Will support for u.

  • Thanks For Simple Tutorial 🙂

  • Thank you for this guide…:))

  • Great example, thank you. Once note ,,, when a new project is created in Android Studio nowadays, the ic_launcher is in R.mipmap, not R.drawable.