Understanding Android Notification

Understanding Android Notification

A notification is a message you can show to the user apart from your application’s standard UI. When you signal the system to give a notification, it initially comes into view as an icon in the notification area. To view the details of the notification, the user clicks on the notification drawer to get it open. Both the notification region and the notification drawer are system-controlled regions that the user can look at any time.

Design reflections

Notifications, as a crucial section of the Android user interface, possess their own design principles. The material design alterations introduced in Android 5.0 (API level 21) are of specific significance, and you ought to review the Material Design tutorial to get extra information with regards to this.

Generating a Notification

You state the UI information and actions for a notification in a NotificationCompat.Builder object. To generate the notification itself, you call NotificationCompat.Builder.build(), which send back a Notification object that bears your specifications. To give the notification, you pass the Notification object to the system by calling NotificationManager.notify().

Needed notification contents

A Notification object ought to contain the following:

A minute icon, set by setSmallIcon()

A title, set by setContentTitle()

A detailed text, set by setContentText()

Non-compulsory notification contents and settings.

Every other notification settings and contents are non compulsory.

Notification actions

Notwithstanding the fact they are not compulsory, you ought to add at least one action to your notification. An action permits users to move straight from the notification to an Activity in your application, where they can appear at one or more events or carry out more work.

A notification can make available a lot of actions. You ought to constantly define the action that’s engendered when the user clicks the notification; normally this action opens an Activity in your application.

You can as well incorporate buttons to the notification that carry out extra actions like snoozing an alarm or reacting straight away to a text message; this feature is accessible as of Android 4.1. If you make use of extra action buttons, you ought to as well make their functionality accessible in an Activity in your app. Within a Notification, the action itself is defined by a PendingIntent bearing an Intent  which begins an Activity in your application. To link the PendingIntent with a gesture, call the suitable technique of NotificationCompat.Builder. For instance, if you want to begin Activity when the user clicks the notification text in the notification drawer, you affix the PendingIntent by calling setContentIntent().

Initiating an Activity when the user clicks the notification is the most basic action situation. You can as well initiate an Activity when the user dismisses a notification. In Android 4.1 and subsequent ones, you can trigger off an Activity from an action button.

Notification precedence

You can set the precedence of a notification. The precedence functions as a hint to the device UI about how the notification ought to be displayed. To set a notification’s precedence, call NotificationCompat.Builder.setPriority () and pass in one of the NotificationCompat priority constants. There are five priority levels, ranging from PRIORITY_MIN (-2) to PRIORITY_MAX (2); if not set, the priority defaults to PRIORITY_DEFAULT (0).

Creating an easy notification

The snippet below shows a straightforward notification that indicates an activity to open when the user clicks the notification. Observe that the code produces a TaskStackBuilder object and makes use of it to develop the PendingIntent for the action.

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
  .setSmallIcon(R.drawable.notification_icon
  .setContentTitle("My notification")
  .setContentText("Hello World!");

// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);

// The stack builder object will contain an artificial back stack for the  started Activity.

// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());

That’s it. Your user has now been notified.

Applying an expanded layout to a notification

To possess a notification appear in an expanded view, initially create a NotificationCompat.Builder object with the standard view options you desire. After that, call Builder.setStyle() with an expanded layout object as its argument. Keep in mind that extended notifications are not accessible on platforms before Android 4.1. The code snippet below illustrates the way to change the notification generated in the last snippet to make use the extended layout:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("Event tracker")
    .setContentText("Events received")
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
String[] events = new String[6];
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle("Event tracker details:");
...
// Moves events into the expanded layout
for (int i=0; i < events.length; i++) {
    inboxStyle.addLine(events[i]);
}
// Moves the expanded layout object into the notification object.
mBuilder.setStyle(inBoxStyle);
...
// Issue the notification here.

 Taking care of compatibility

Not all notification features are accessible for a specific edition, although the techniques to set them are in the support library category NotificationCompat.Builder. For instance, action buttons, which depend on expanded notifications, merely appear on Android 4.1 and higher, due to extended notifications themselves are merely accessible on Android 4.1 and later editions.

To obtain the best compatibility, generate notifications with NotificationCompat and its subcategories, especially NotificationCompat.Builder. Again, follow the procedure below anytime you implement a notification:

– Make available all of the notification’s features to all users, irrespective of the edition they are making use. To achieve this, ensure that every one of the features are accessible from an Activity in your app. You may wish to incoporate a new Activity to achieve this.

For instance, if you want to make use of addAction() to create a control that ends and begins media playback, initially carry out this control in an Activity in your app.

– Make sure that every one of the users can have access to the features in the Activity, through making it to be able to kick off when users click the notification. To achieve this, generate a PendingIntent for the Activity. Call setContentIntent() to incorporate the PendingIntent to the notification.

– At this point, incorporate the extended notification features you wish to make use of to the notification. Bear in mind that that any functionality you incorporate is as well accessible in the Activity that begins when users click the notification.

Managing Notifications

When you require to give a notification many times for an equivalent type of event, you ought to avoid making an entirely new notification. Rather, you ought to think about updating an earlier notification, either by altering a few of its values or by adding to it, or both.

For instance, Gmail signals the user that new emails have been received by increasing its count of unread messages and by incorporating a rundown of every email to the notification. This is known as “stacking” the notification.

This Gmail feature needs the “inbox” expanded layout, which is part of the expanded notification feature accessible beginning with Android 4.1.

The section below explains the way to carry out update notifications and as well the way to take them away.

Updating notifications

To create a notification in order that it could be kept up to date create it with a notification ID by calling NotificationManager.notify(). To update this notification immediately you have produced it, update or create a NotificationCompat.Builder object, create a Notification object from it, and issue the Notification with the same ID you made use of earlier. If the earlier notification is still seen, the system updates it from the contents of the Notification object. If the earlier notification has been discarded, a fresh notification is rather produced.

The snippet below shows a notification that is kept up to date to reflect the number of events that have taken place. It stacks the notification, illustrating a summary:

mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
    .setContentTitle("New Message")
    .setContentText("You've received new messages.")
    .setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
    mNotifyBuilder.setContentText(currentText)
        .setNumber(++numMessages);
    // Because the ID remains unchanged, the existing notification is
    // updated.
    mNotificationManager.notify(
            notifyID,
            mNotifyBuilder.build());
...

 Removing notifications

Notifications will continue to be seen till such a time one of the things below occur:

– user discards the notification either singularly or by the use of “Clear All” (if the notification can be cleaned up).

– The user clicks the notification, and you called setAutoCancel() when you generated the notification.

– You call cancel() for a particular notification ID. This method as well deletes ongoing notifications.

– You call cancelAll(), which takes away every one of the notifications you earlier issued.

Preserving Navigation when Starting an Activity

When you initiate an Activity from a notification, you ought to conserve the user’s expected navigation experience. Clicking Back ought to return the user back via the application’s standard work flow to the Home screen, and clicking Recents ought to bring into view the Activity as a different task. To conserve the navigation experience, you ought to begin the Activity in a fresh task. How you set up the PendingIntent to offer you a fresh task depends on the nature of the Activity you’re initiating. There are two wide-ranging situations:

Standard activity

You’re initiating an Activity that’s part of the application’s standard workflow. In this instance, set up the PendingIntent to begin a fresh task, and offer the PendingIntent with a back stack that reproduces the application’s standard Back behavior.

Notifications from the Gmail app illustrate this. When you click a notification for a unique email message, you view the message itself. Touching Back takes you backwards via Gmail to the Home screen, the same way as if you had entered Gmail from the Home screen instead of entering it from a notification.

This occurs irrespective of the application you were in when you touched the notification. For instance, if you’re in Gmail composing a message, and you click a notification for one email, you enter straight away into that email. Touching Back returns you to the inbox and then the Home screen, instead of taking you to the message you were composing.

With Android 5.0 (API level 21), notifications can be visible in a small floating window as well known as a heads-up notification when the device is active. This means when the device is unlocked and its screen is on. These notifications look similar to the compact form of your notification, apart from that the heads-up notification as well illustrates action buttons. Users can take action on, or discards, a heads-up notification without leaving the present app.

Examples of conditions that may kick off heads-up notifications are:

– The user’s activity is in full screen mode (the app makes use of fullScreenIntent), or

– The notification possess top precedence and makes use of ringtones or vibrations

 Notification Manager

Android allows you to put notification into the titlebar of your application. The user can enlarge the notification bar and by selecting the notification the user can activate another activity.

 Setting up Notifications

Notifications in Android are symbolized by the Notification class. To generate notifications you make use of the NotificationManager category which can be obtained from theContext, such as an activity or a service, through the getSystemService() method.

NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

The Notification.Builder makes available a builder interface to generate a Notificationobject. You make use of a PendingIntent to denote the action which ought to carried out once the user chose the notification.

The Notification.Builder permits you to add up to three buttons with definable actions to the notification.

// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test@gmail.com")
.setContentText("Subject")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);

OTHER INTERESTING POSTS:

Add a Comment