Search This Blog

Monday 2 July 2012

Basics of Notifications in Andoird

Android provides the notification APIs for applications to push the notifications for the user on the device.

Toast Notification


The toast notifications invoke on the surface of the window.You can invoke the toast notifications from the Activity or Service.The Toast notifications acquire the area equivalent to the message and automatically fades. The user current activity is interactive upon the display of the toast notification.

The toast notification doesn't provide any interaction to the user. They are only useful to send the read only messages as notification to the user.

Create the simple toast notification in your activity class.

Context context = getApplicationContext();
CharSequence text = "Hi,I am a toast notification";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();
 

Status Bar Notification

The status bar notification provides the interaction with the user. The notifications which need a response from the end user should add to the status bar notifications. A status notification add a icon to the system status bar and a notification message in the notification window.

When user selects the notification the android fires and Intent  to launch the Activity defined by notification.

The sound,vibration or flashing lights could also be used for notification.

The background services need to notify the event which needs user response in the status notification.

The status notifications are managed in android using Notification and NotificationManager classes. 

The Notification class defines the notification which includes the status icon, message and the action (Activity to start as response from user).

The Notification manager class manages the notification system service and handle all the status bar notifications in android.

To create a simple status notification you can follow the following steps

Get a instance of the Notification manager as follows

String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =  
(NotificationManager) getSystemService(ns);

Now create a notification object as follows

int icon = R.drawable.notification_icon;
CharSequence tickerText = "StatusBar";
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);

Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, LanuchAsResponse.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
 
Now notify the notification to the status bar as follows

private static final int SAMPLE_ID = 1;

mNotificationManager.notify(SAMPLE_ID, notification);

 
 





No comments:

Post a Comment