Android 4.1 Jelly Bean Notification Tutorial


Notifications have always been very interesting feature of android. Developers can use them to present important event information in front of user in notification bar, outside of the application’s UI.

Jelly Beans brings mejor enhancements in notification, no application larger, richer notifications that can be expanded and collapsed with a pinch or swipe. Notifications support new types of content, including photos, have configurable priority, and can even include multiple actions.

Let us have a look at few of the samples…

Just like older versions we still got to get the NotificationManager to show any notification.

Next step would be to initiate the Notification. Let us initiate a very simple notification and see how it looks.

For the simplest notification, we will need to set at least a small icon.

Displaying a notification requires us to set an ID for the notification.

package com.example.notificationtest;

import java.io.BufferedInputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {

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

		BufferedInputStream buf;
		try {
			buf = new BufferedInputStream(getAssets().open("me.jpeg"));

			// Create the bitmap to be set in notification.
			Bitmap bitmap = BitmapFactory.decodeStream(buf);
			buf.close();

			// Pending intent to be fired when notification is clicked
			Intent intent = new Intent(this, MainActivity.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(this, 01,
					intent, Intent.FLAG_ACTIVITY_CLEAR_TASK);

			// Get the builder to create notification.
			Builder builder = new Notification.Builder(getApplicationContext());
			// Set the first line of text in the platform notification template.
			builder.setContentTitle("Content Title");
			// Set the second line of text in the platform notification
			// template.
			builder.setContentText("Content Text");
			// Set the third line of text in the platform notification template.
			// Don't use if you're also using setProgress(int, int, boolean);
			// they occupy the same location in the standard template.
			builder.setSubText("Sub Text");
			// Set the large number at the right-hand side of the notification.
			// This is equivalent to setContentInfo, although it might show the
			// number in a different font size for readability.
			builder.setNumber(100);
			// Set the "ticker" text which is displayed in the status bar when
			// the notification first arrives.
			builder.setTicker("Notification by Chitranshu Asthana");
			// Set the small icon resource, which will be used to represent the
			// notification in the status bar. The platform template for the
			// expanded view will draw this icon in the left, unless a large
			// icon has also been specified, in which case the small icon will
			// be moved to the right-hand side.
			builder.setSmallIcon(R.drawable.ic_launcher);
			// Add a large icon to the notification (and the ticker on some
			// devices). In the platform template, this image will be shown on
			// the left of the notification view in place of the small icon
			// (which will move to the right side).
			builder.setLargeIcon(bitmap);
			// Supply a PendingIntent to send when the notification is cleared
			// explicitly by the user.
			builder.setDeleteIntent(pendingIntent);
			// Make this notification automatically dismissed when the user
			// touches it. The PendingIntent set with
			// setDeleteIntent(PendingIntent) will be sent when this happens.
			builder.setAutoCancel(true);
			// Set the priority of this notification.
			builder.setPriority(0);

			// Combine all of the options that have been set and return a new
			// Notification object.
			Notification notification = builder.build();

			NotificationManager notificationManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			// Post a notification to be shown in the status bar. If a
			// notification with the same id has already been posted by your
			// application and has not yet been canceled, it will be replaced by
			// the updated information.
			notificationManger.notify(01, notification);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

 

Well that looks good. Now let us have a look at what else Jelly Beans has.

In addition to the templated styles, we can create our own notification styles using any remote View.

Let us extend the previous code and create 2 different notifications and lets see how it looks.

Let us create a layout for out notification.

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

    <ImageView
        android:id="@+id/notification_main_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/me" />

    <TextView
        android:id="@+id/notification_main_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_toRightOf="@id/notification_main_img"
        android:text="Notification from remote view" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/notification_main_img"
        android:layout_below="@id/notification_main_txt"
        android:layout_toRightOf="@id/notification_main_img"
        android:orientation="horizontal"
        android:weightSum="2" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/notification_main_img"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Sub Text 1" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/notification_main_img"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Sub Text 2" />
    </LinearLayout>

</RelativeLayout>

 

Now let us look at the code with two different notifications.

package com.example.notificationtest;

import java.io.BufferedInputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.widget.RemoteViews;

public class MainActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		{
			BufferedInputStream buf;
			try {
				buf = new BufferedInputStream(getAssets().open("me.jpeg"));

				// Create the bitmap to be set in notification.
				Bitmap bitmap = BitmapFactory.decodeStream(buf);
				buf.close();

				// Pending intent to be fired when notification is clicked
				Intent intent = new Intent(this, MainActivity.class);
				PendingIntent pendingIntent = PendingIntent.getActivity(this,
						01, intent, Intent.FLAG_ACTIVITY_CLEAR_TASK);

				// Get the builder to create notification.
				Builder builder = new Notification.Builder(
						getApplicationContext());
				// Set the first line of text in the platform notification
				// template.
				builder.setContentTitle("Content Title");
				// Set the second line of text in the platform notification
				// template.
				builder.setContentText("Content Text");
				// Set the third line of text in the platform notification
				// template.
				// Don't use if you're also using setProgress(int, int,
				// boolean);
				// they occupy the same location in the standard template.
				builder.setSubText("Sub Text");
				// Set the large number at the right-hand side of the
				// notification.
				// This is equivalent to setContentInfo, although it might show
				// the
				// number in a different font size for readability.
				builder.setNumber(100);
				// Set the "ticker" text which is displayed in the status bar
				// when
				// the notification first arrives.
				builder.setTicker("Notification by Chitranshu Asthana");
				// Set the small icon resource, which will be used to represent
				// the
				// notification in the status bar. The platform template for the
				// expanded view will draw this icon in the left, unless a large
				// icon has also been specified, in which case the small icon
				// will
				// be moved to the right-hand side.
				builder.setSmallIcon(R.drawable.ic_launcher);
				// Add a large icon to the notification (and the ticker on some
				// devices). In the platform template, this image will be shown
				// on
				// the left of the notification view in place of the small icon
				// (which will move to the right side).
				builder.setLargeIcon(bitmap);
				// Supply a PendingIntent to send when the notification is
				// cleared
				// explicitly by the user.
				builder.setDeleteIntent(pendingIntent);
				// Make this notification automatically dismissed when the user
				// touches it. The PendingIntent set with
				// setDeleteIntent(PendingIntent) will be sent when this
				// happens.
				builder.setAutoCancel(true);
				// Set the priority of this notification.
				builder.setPriority(1);

				// Combine all of the options that have been set and return a
				// new
				// Notification object.
				Notification notification = builder.build();

				NotificationManager notificationManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				// Post a notification to be shown in the status bar. If a
				// notification with the same id has already been posted by your
				// application and has not yet been canceled, it will be
				// replaced by
				// the updated information.
				notificationManger.notify(01, notification);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		{

			// Pending intent to be fired when notification is clicked
			Intent intent = new Intent(this, MainActivity.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(this, 01,
					intent, Intent.FLAG_ACTIVITY_CLEAR_TASK);
			RemoteViews remoteViews = new RemoteViews(getPackageName(),
					R.layout.notification_layout);
			Builder builder = new Notification.Builder(getApplicationContext());
			// Set the small icon resource, which will be used to represent the
			// notification in the status bar. The platform template for the
			// expanded view will draw this icon in the left, unless a large
			// icon has also been specified, in which case the small icon will
			// be moved to the right-hand side.
			builder.setSmallIcon(R.drawable.ic_launcher);
			// Supply a custom RemoteViews to use instead of the platform
			// template.
			builder.setContent(remoteViews);
			// Set the "ticker" text which is displayed in the status bar
			// when
			// the notification first arrives.
			builder.setTicker("Notification by Chitranshu Asthana (Remote View)");
			// Supply a PendingIntent to send when the notification is
			// cleared
			// explicitly by the user.
			builder.setDeleteIntent(pendingIntent);
			// Make this notification automatically dismissed when the user
			// touches it. The PendingIntent set with
			// setDeleteIntent(PendingIntent) will be sent when this
			// happens.
			builder.setAutoCancel(true);
			// Set the priority of this notification.
			builder.setPriority(0);

			// Combine all of the options that have been set and return a
			// new
			// Notification object.
			Notification notification = builder.build();

			NotificationManager notificationManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			// Post a notification to be shown in the status bar. If a
			// notification with the same id has already been posted by your
			// application and has not yet been canceled, it will be
			// replaced by
			// the updated information.
			notificationManger.notify(02, notification);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

 

Thats really interesting.. 🙂

Advertisements

3 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s