Android Custom Notification Tutorial

In this tutorial, you will learn how to create Custom Notifications in your Android application. A notification is a message you can display to the user outside of your Android application. Notifications can be clicked to perform an action or to open a new activity. We will be creating a custom notification and a simple notification and on notification click will show results on a new activity. So lets begin…

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project NotificationTutorial.

Application Name : NotificationTutorial

Project Name : NotificationTutorial

Package Name : com.androidbegin.notificationtutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.notificationtutorial;

import android.os.Bundle;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;

public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notificationmain);

		Button bnotify = (Button) findViewById(R.id.notification);

		Button bcustomnotify = (Button) findViewById(R.id.customnotification);

		bnotify.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				Notification();
				// TODO Auto-generated method stub
			}
		});

		bcustomnotify.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				CustomNotification();
				// TODO Auto-generated method stub
			}
		});

	}

	public void Notification() {
		// Set Notification Title
		String strtitle = getString(R.string.notificationtitle);
		// Set Notification Text
		String strtext = getString(R.string.notificationtext);

		// Open NotificationView Class on Notification Click
		Intent intent = new Intent(this, NotificationView.class);
		// Send data to NotificationView Class
		intent.putExtra("title", strtitle);
		intent.putExtra("text", strtext);
		// Open NotificationView.java Activity
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		//Create Notification using NotificationCompat.Builder 
		NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
				// Set Icon
				.setSmallIcon(R.drawable.logosmall)
				// Set Ticker Message
				.setTicker(getString(R.string.notificationticker))
				// Set Title
				.setContentTitle(getString(R.string.notificationtitle))
				// Set Text
				.setContentText(getString(R.string.notificationtext))
				// Add an Action Button below Notification
				.addAction(R.drawable.ic_launcher, "Action Button", pIntent)
				// Set PendingIntent into Notification
				.setContentIntent(pIntent)
				// Dismiss Notification
				.setAutoCancel(true);

		// Create Notification Manager
		NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		// Build Notification with Notification Manager
		notificationmanager.notify(0, builder.build());

	}

	public void CustomNotification() {
		// Using RemoteViews to bind custom layouts into Notification
		RemoteViews remoteViews = new RemoteViews(getPackageName(),
				R.layout.customnotification);

		// Set Notification Title
		String strtitle = getString(R.string.customnotificationtitle);
		// Set Notification Text
		String strtext = getString(R.string.customnotificationtext);

		// Open NotificationView Class on Notification Click
		Intent intent = new Intent(this, NotificationView.class);
		// Send data to NotificationView Class
		intent.putExtra("title", strtitle);
		intent.putExtra("text", strtext);
		// Open NotificationView.java Activity
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
				// Set Icon
				.setSmallIcon(R.drawable.logosmall)
				// Set Ticker Message
				.setTicker(getString(R.string.customnotificationticker))
				// Dismiss Notification
				.setAutoCancel(true)
				// Set PendingIntent into Notification
				.setContentIntent(pIntent)
				// Set RemoteViews into Notification
				.setContent(remoteViews);

		// Locate and set the Image into customnotificationtext.xml ImageViews
		remoteViews.setImageViewResource(R.id.imagenotileft,R.drawable.ic_launcher);
		remoteViews.setImageViewResource(R.id.imagenotiright,R.drawable.androidhappy);

		// Locate and set the Text into customnotificationtext.xml TextViews
		remoteViews.setTextViewText(R.id.title,getString(R.string.customnotificationtitle));
		remoteViews.setTextViewText(R.id.text,getString(R.string.customnotificationtext));

		// Create Notification Manager
		NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		// Build Notification with Notification Manager
		notificationmanager.notify(0, builder.build());

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

We have created two buttons in this application, the first button will show a simple notification and the other will show a custom notification. Both notifications are created using NotificationCompat.Builder. Using NotificationCompat.Builder allows you to build your application below Android Version 4.1. A PendingIntent allows notifications to be clicked or to open a new activity. We have prepared a sample custom notification image for this tutorial. Put your downloaded sample images into your res > drawable-hdpi.

Sample Image

[wpfilebase tag=file id=44 tpl=download-button /]

Next, create an XML file graphical layout for your MainActivity. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file notificationmain.xml and paste the following code.

notificationmain.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/notification" />

    <Button
        android:id="@+id/customnotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_below="@+id/notification"
        android:text="@string/customnotification" />

</RelativeLayout>

Output:

NotificationMain XML

Next, create an XML graphical layout for your Custom Notification. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file customnotification.xml and paste the following code.

customnotification.xml 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imagenotileft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/imagenotileft" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/imagenotileft" />

    <ImageView
        android:id="@+id/imagenotiright"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:padding="10dp" />

</RelativeLayout>

Next, create an activity to view notification click results. Go to File > New > Class and name it NotificationView.java. Select your package named com.androidbegin.notificationtutorial and click Finish.

Open your NotificationView.java and paste the following code.

NotificationView.java

package com.androidbegin.notificationtutorial;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class NotificationView extends Activity {
	String title;
	String text;
	TextView txttitle;
	TextView txttext;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notificationview);

		// Create Notification Manager
		NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		// Dismiss Notification
		notificationmanager.cancel(0);

		// Retrive the data from MainActivity.java
		Intent i = getIntent();

		title = i.getStringExtra("title");
		text = i.getStringExtra("text");

		// Locate the TextView
		txttitle = (TextView) findViewById(R.id.title);
		txttext = (TextView) findViewById(R.id.text);

		// Set the data into TextView
		txttitle.setText(title);
		txttext.setText(text);
	}
}

Next, create an XML graphical layout for your NotificationView. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file notificationview.xml and paste the following code.

notificationview.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/lbltitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lbltitle" />

    <TextView
        android:id="@+id/lbltext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/lbltitle"
        android:text="@string/lbltext" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/lbltitle" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/lbltext" />

</RelativeLayout>

Change the application name and texts in strings.xml. Open your strings.xml and paste the following code. Go to res > values > strings.xml

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Notification Tutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="notificationtitle">Android Notification Tutorial</string>
    <string name="notificationtext">Notification Text</string>
    <string name="notificationticker">Notification Ticker</string>
    <string name="customnotificationtitle">Android Notification Tutorial</string>
    <string name="customnotificationtext">Custom Notification Text</string>
    <string name="customnotificationticker">Custom Notification Ticker</string>
    <string name="lbltitle">"Title : "</string>
    <string name="lbltext">"Text : "</string>
    <string name="notification">Notification</string>
    <string name="customnotification">Custom Notification</string>

</resources>

In your AndroidManifest.xml, we need to declare an activity. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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=".NotificationView" >
        </activity>
    </application>

</manifest>

Output:

Android Notification Tutorial ScreenShot

Source Code

[purchase_link id=”7934″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

by adding action like this custom notification donot show title and text: Intent stopreciver = new Intent(); stopreciver.setAction("STOP_ACTION"); PendingIntent pendingIntentYes2 = PendingIntent.getBroadcast(this, 12345, stopreciver, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(R.drawable.androidhappy, getResources().getString(R.string.app_name), pendingIntentYes2);

Sajad Mohamadi

Android Custom Notification Tutorial

I take the same code but add action dosen't work i dont either see the button

dadou zaidi

Android Custom Notification Tutorial

i want to create custom notification like youtube video download...with progress bar...can you please help?

Android Developer

Android Custom Notification Tutorial

Why doesn't the notification stay on the tray. on Android 5.1.1 and up? You have to make it .setOngoing(true) to stay but then it will not swipe dismiss. Any clue as to why this is happening?

Ed Burch

Android Custom Notification Tutorial