Wednesday, May 25, 2016

Generate Local Notification in Android

Generate local notification like Remainder or other scheduling task.

Call generateNotification Method and set Title and Message.
    Generate Local Notification
private void generateNotification(Context context, String title,String message) {
int requestId = (int) System.currentTimeMillis();
try {
int icon = R.drawable.ic_launcher; // set icon
Intent intent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context);
Notification notification = mBuilder
.setSmallIcon(icon)
.setTicker(title)
.setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(
new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentIntent(resultPendingIntent)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(
BitmapFactory.decodeResource(
context.getResources(), icon))
.setContentText(message).build();

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;

NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(requestId, notification);
} catch (Exception e) {
}

}

Show Notification
Send Notification


No comments :

Post a Comment