Saturday, March 9, 2013

Android notifications

Notifications are great.  Instead of manually opening an app and checking for updates (to see if you have any new emails or text messages), your smart phone works in the background and sends you alerts when updates are available.

I created a simple notification ( the one on top is mine ).

Here is some code to set up a simple notification:
// Set which activity is opened when you click on 
// the notification in the notification bar.
// You can just re-open your app.
Intent intent = new Intent(this, MainActivity.class);

// Set these flags to re-open your app. If it's not
// killed you won't create a new activity.
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP );

// Make the pending intent. Give this to the notification
// so that your activity can be called.
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// Build the notification.
// With a title, text, and pending intent.
Notification notification = new Notification.Builder(this)
.setContentTitle("Alert! You are notified.")
.setContentText("Click to open app.")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.build();

// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL ;

NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);

There are lots of bells and whistles (literally) that can be added to your notifications (I think).  This simple code demonstrates how simple it is to create a simple notification.

Resources:
http://www.vogella.com/articles/AndroidNotifications/article.html

No comments:

Post a Comment