
A status bar notification allows user to notify an event without interrupting their current activity. Also, we can attach Intent to the notification, and the system will initiate the intent when the user clicks on the notification.
A status bar notification adds an icon to the
system's status bar with an optional ticker-text message and a notification
message in the notifications window. When the user selects the notification,
Android fires an Intent that is defined by the Notification usually to launch
an Activity. You can also configure the notification to alert the user with a
sound, a vibration, and flashing lights on the device.
Here, in this tutorial I will demonstrate
creating the status bar notification from the application and the basics responding
to notification. For creating user notifications we will require to use Notification and
NotificationManager class.
Here are
the steps to create a status bar notification:
1. Get a reference to the NotificationManager
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2. Instantiate the Notification: It
takes the notification icon, notification text and the delay time in milliseconds
to display the notification.
Notification notification = new Notification(R.drawable.block_user_icon, "Block
user",
System.currentTimeMillis());
3. Define the notification's message
and PendingIntent. The PendingIntent will launch activity if the user selects
this notification. Here you can have your activity class reference. I am using
PendingIntent
contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new
Intent(getApplicationContext(), LoginScreen.class), 0);
notification.setLatestEventInfo(getApplicationContext(),
"Title here", ".. And here's some more details..",
contentIntent);
4. Pass the Notification to the NotificationManager:
manager.notify(YOURAPP_NOTIFICATION_ID,
notification);
That's
it. Your user has now been notified.
5.
To Cancel/Remote the notification from status bar
manager.cancel(YOURAPP_NOTIFICATION_ID);