Android – Send Notification Code

The following code will send a notification, which will display in the status bar. Note that the Notification.FLAG_AUTO_CANCEL line (about line 8) will remove the notification when the user clicks it.


{

String ns = Context.NOTIFICATION_SERVICE;
 NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
 int icon = R.drawable.icon;
 CharSequence tickerText = "Notification";
 long when = System.currentTimeMillis();
 Notification notification = new Notification(icon, tickerText, when);
 notification.flags = Notification.FLAG_AUTO_CANCEL;
 Context context = getApplicationContext();
 CharSequence contentTitle = "Notification";
 CharSequence contentText = notifications[getRandomNumber()];
 Intent notificationIntent = new Intent(this, MyTestApp.class);
 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
 notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

final int NOTIFY_ID = 1;
 mNotificationManager.notify(NOTIFY_ID, notification);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s