October 15, 2015 Julie raiyani 5 Comments

Android allows user to notify on new message arrived as well as some calendar – based events by notification.Notification is a user interface element that will display outside of any other app’s normal UI to indicate that an event has occurred. Users can choose to view the notification while using other apps and respond to it when it’s convenient for them.

Android notification will be displayed in the Notification area and to see the details regarding the notification, the user can expand it in by open the Notification drawer.

We will discuss about Local notification and Heads Up Notification here.

To Create Notification :

To create notification we have to use NotificationCompat.Builder’s object. Notification itself build by NotificationCompat.Builder.build(), which returns a Notification object containing with specifications of notification.

A Notification object must contain setSmallIcon() to set a small icon, setContentTitle() to set title and setContentText() to set detailed text. Another settings and contents are optional.

To set action like as call another activity directly by clicking on the notification, we have to use PendingIntent with containing an Intent which starts an Activity of our application.

We can set notification priority using NotificationCompat.Builder.setPriority() by passing one of the NotificationCompatpriority constants.

There are five priority levels like as below:

1) PRIORITY_MAX =2

2) PRIORITY_HIGH =1

3) PRIORITY_DEFAULT =0

4) PRIORITY_LOW =-1

5) PRIORITY_MIN=-2

Here is a code to create notification:

[cc lang=”java”] //build notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(“Simple notification”)
.setContentText(“This is test of simple notification.”);
// Gets an instance of the NotificationManager service
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//to post your notification to the notification bar
notificationManager.notify(0 , mBuilder.build());
[/cc]

Expand Layout of a Notification:

To expand the layout of notification we have to use Builder.setStyle() with NotificationCompat.Builder object.

Note: Expanded notifications are not available on platforms prior to Android 4.1.

There are different types of expanded notification as below :

1) Inbox Style Notification:

When you want to display multiline text detail section, you can use NotificationCompat.InboxStyle

Here is example code of inbox style notification:

[cc lang=”java”] //set intents and pending intents to call activity on click of “show activity” action button of notification
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent piResult = PendingIntent.getActivity(this,
(int) Calendar.getInstance().getTimeInMillis(), resultIntent, 0);

//Assign inbox style notification
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();

inboxStyle.setBigContentTitle(“Inbox Notification”);
inboxStyle.addLine(“Message 1.”);
inboxStyle.addLine(“Message 2.”);
inboxStyle.addLine(“Message 3.”);
inboxStyle.addLine(“Message 4.”);
inboxStyle.addLine(“Message 5.”);
inboxStyle.setSummaryText(“+2 more”);

//build notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(“Inbox style notification”)
.setContentText(“This is test of inbox style notification.”)
.setStyle(inboxStyle)
.addAction(R.drawable.ic_input_black_18dp, “show activity”, piResult);

// Gets an instance of the NotificationManager service
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//to post your notification to the notification bar
notificationManager.notify(0, mBuilder.build());
[/cc]

2) Big Text Style Notification:

When you have a large text block in detail section of text you can use NotificationCompat.BigTextStyle

Here is example code of Big Text style notification:

[cc lang=”java”] //To set large icon in notification
Bitmap icon1 = BitmapFactory.decodeResource(getResources(),
R.drawable.big_image);

//Assign inbox style notification
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(“Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.”);
bigText.setBigContentTitle(“Big Text Notification”);
bigText.setSummaryText(“By: Author of Lorem ipsum”);

//build notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(“Big Text notification”)
.setContentText(“This is test of big text style notification.”)
.setLargeIcon(icon1)
.setStyle(bigText);

// Gets an instance of the NotificationManager service
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//to post your notification to the notification bar
mNotificationManager.notify(0, mBuilder.build());
[/cc]

3)  Big Picture Style Notification:

When you have a large format in which you want to display a big image you can use NotificationCompat.BigPictureStyle

The big picture contains a bitmap up to 256 dip tall in its detail section.

Here is example code of Big Picture style notification:

[cc lang=”java”]
//build notification
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(“Big picture notification”)
.setContentText(“This is test of big picture notification.”)
.setStyle(bigPictureStyle)
.addAction(R.drawable.ic_input_black_18dp, “show activity”, piResult)
.addAction(R.drawable.ic_share_black_18dp, “Share”,
PendingIntent.getActivity(getApplicationContext(), 0,
getIntent(), 0, null));
//set intents and pending intents to call activity on click of “show activity” action button of notification
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent piResult = PendingIntent.getActivity(this,
(int) Calendar.getInstance().getTimeInMillis(), resultIntent, 0);

// Assign big picture notification
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();

bigPictureStyle.bigPicture(
BitmapFactory.decodeResource(getResources(),
R.drawable.big_image)).build();

// Gets an instance of the NotificationManager service
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//to post your notification to the notification bar
notificationManager.notify(0, builder.build());
[/cc]

Schedule using AlarmManager and broadcast Notification

Sometimes the user needs to schedule a notification to notify a user at a particular date/time, even though the user has not opened the application. For this, we have to use BroadcastReceiver of Android SDK. We will discuss BroadcastRreceiver below.

In addition to the above class, we also have to use AlarmManager class to schedule and add events. AlarmManager has access to the system alarm services. With the help of it, you can schedule execution of code in future.

AlarmManager object can’t instantiate directly however it can be retrieved by calling Context.getSystemService(Context.ALARM_SERVICE). AlarmManager is always registered with Intent. When an alarm goes off, the Intent which has been registered with AlarmManager is broadcasted by the system automatically. This intent starts the target application if it is not running. It is recommended to use AlarmManager when you want your application code to be run at a specific time, even if your application is not currently running.

Here is example code of Schedule notification:

[cc lang=”java”] //set intents and pending intents to call activity on click of “show activity” action button of notification
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent piResult = PendingIntent.getActivity(this,
(int) Calendar.getInstance().getTimeInMillis(), resultIntent, 0);

// Assign big picture notification
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();

bigPictureStyle.bigPicture(
BitmapFactory.decodeResource(getResources(),
R.drawable.big_image)).build();

//build notification
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(“Big picture notification”)
.setContentText(“This is test of big picture notification.”)
.setStyle(bigPictureStyle)
.addAction(R.drawable.ic_input_black_18dp, “show activity”, piResult)
.addAction(R.drawable.ic_share_black_18dp, “Share”,
PendingIntent.getActivity(getApplicationContext(), 0,
getIntent(), 0, null));

// Gets an instance of the NotificationManager service
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//to post your notification to the notification bar
notificationManager.notify(0, builder.build());
[/cc]

Now create BroadcastReceiver.

A Broadcast Receiver (short receiver) allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.

[cc lang=”java”] public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;

@Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = “Schedule notification”;
CharSequence message = “This is test of Schedule notification”;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.snooze,
“Test Schedule notification”, System.currentTimeMillis());
notif.defaults = Notification.DEFAULT_ALL;
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
}

}

[/cc]

At last, don’t forget to register BroadcastReceiver class in AndroidManifest.xml

<receiver android:name=”.TimeAlarm” />

5 People reacted on this

  1. Excellent post. I was checking constantly this blog and I’m impressed! Very useful info specifically the last part 🙂 I care for such info a lot. I was looking for this particular information for a very long time. Thank you and good luck.

  2. Everything is very open with a very clear description of the issues.
    It was really informative. Your website is very
    useful. Many thanks for sharing!

  3. I just want to tell you that I am newbie to weblog and actually loved you’re blog site. Most likely I’m going to bookmark your site . You surely have great well written articles. Bless you for sharing with us your web-site.

  4. Great wordpress blog here.. It’s hard to find quality writing like yours these days. I really appreciate people like you! take care

Comments are closed.