Send Notifications in Android


Today I am going to show you how to send a user notification in Android.
Go through below code snippets and comments.


public void sendNotification() {
//Start notification sending
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) this.getApplicationContext().getSystemService(ns); int icon = R.drawable.notification_icon;
//you should added notification icon to drawable folder.
CharSequence tickerText = getString(R.string.notification_bar_text);
//You should define text in res->values->string.xml
long when = System.currentTimeMillis();
Context context = getApplicationContext();
CharSequence contentTitle = getString(R.string.notification_bar_text);
CharSequence contentText = "Hello World";
// when the notification is clicked, following Activity starts
Intent notificationIntent = new Intent(this,
MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
notification.defaults = Notification.DEFAULT_SOUND;
notification.flags = Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(1, notification);
//End notification sending
}


Happy coding.

Comments

Popular Posts