How to display multiple notification as a group? - android

here is my code for notification. it generate a new notification each time
Random random = new Random();
int m = random.nextInt(9999 - 1000);
NotificationCompat.Builder mBuilder =new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.quemark1)
.setContentTitle("New Message")
.setContentText(message)
Intent intent = new Intent(this, ActivityMain.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(ActivityMain.class);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);
mNotificationManager.notify(m, mBuilder.build());
here is the output of my code

It will generate notification with multiple messages like Gmail
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.quemark1)
.setContentTitle("Title")
.setContentText("New Message received");
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle("doUdo");
// Add your All messages here or use Loop to generate messages
inboxStyle.addLine("Messgare 1");
inboxStyle.addLine("Messgare 2");
.
.
inboxStyle.addLine("Messgare n");
mBuilder.setStyle(inboxStyle);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);
mNotificationManager.notify(0, mBuilder.build());

When creating notifications for a handheld device, you should always aggregate similar notifications into a single summary notification.
Check this it shows how to build stack notification.
private void sendStackNotificationIfNeeded(RemoteNotification remoteNotification) {
// only run this code if the device is running 23 or better
if (Build.VERSION.SDK_INT >= 23) {
ArrayList<StatusBarNotification> groupedNotifications = new ArrayList<>();
// step through all the active StatusBarNotifications and
for (StatusBarNotification sbn : getNotificationManagerService().getActiveNotifications()) {
// add any previously sent notifications with a group that matches our RemoteNotification
// and exclude any previously sent stack notifications
if (remoteNotification.getUserNotificationGroup() != null &&
remoteNotification.getUserNotificationGroup().equals(sbn.getNotification().getGroup()) &&
sbn.getId() != RemoteNotification.TYPE_STACK) {
groupedNotifications.add(sbn);
}
}
// since we assume the most recent notification was delivered just prior to calling this method,
// we check that previous notifications in the group include at least 2 notifications
if (groupedNotifications.size() > 1) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// use convenience methods on our RemoteNotification wrapper to create a title
builder.setContentTitle(String.format("%s: %s", remoteNotification.getAppName(), remoteNotification.getErrorName()))
.setContentText(String.format("%d new activities", groupedNotifications.size()));
// for every previously sent notification that met our above requirements,
// add a new line containing its title to the inbox style notification extender
NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle();
{
for (StatusBarNotification activeSbn : groupedNotifications) {
String stackNotificationLine = (String)activeSbn.getNotification().extras.get(NotificationCompat.EXTRA_TITLE);
if (stackNotificationLine != null) {
inbox.addLine(stackNotificationLine);
}
}
// the summary text will appear at the bottom of the expanded stack notification
// we just display the same thing from above (don't forget to use string
// resource formats!)
inbox.setSummaryText(String.format("%d new activities", groupedNotifications.size()));
}
builder.setStyle(inbox);
// make sure that our group is set the same as our most recent RemoteNotification
// and choose to make it the group summary.
// when this option is set to true, all previously sent/active notifications
// in the same group will be hidden in favor of the notifcation we are creating
builder.setGroup(remoteNotification.getUserNotificationGroup())
.setGroupSummary(true);
// if the user taps the notification, it should disappear after firing its content intent
// and we set the priority to high to avoid Doze from delaying our notifications
builder.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
// create a unique PendingIntent using an integer request code.
final int requestCode = (int)System.currentTimeMillis() / 1000;
builder.setContentIntent(PendingIntent.getActivity(this, requestCode, DetailActivity.createIntent(this), PendingIntent.FLAG_ONE_SHOT));
Notification stackNotification = builder.build();
stackNotification.defaults = Notification.DEFAULT_ALL;
// finally, deliver the notification using the group identifier as the Tag
// and the TYPE_STACK which will cause any previously sent stack notifications
// for this group to be updated with the contents of this built summary notification
getNotificationManagerService().notify(remoteNotification.getUserNotificationGroup(), RemoteNotification.TYPE_STACK, stackNotification);
}
}
}

From https://developer.android.com/training/notify-user/group.
String GROUP_KEY_WORK_EMAIL = "com.android.example.WORK_EMAIL";
Notification newMessageNotification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setSmallIcon(R.drawable.new_mail)
.setContentTitle(emailObject.getSenderName())
.setContentText(emailObject.getSubject())
.setLargeIcon(emailObject.getSenderAvatar())
.setGroup(GROUP_KEY_WORK_EMAIL)
.build();
By default, notifications are sorted according to when they were posted, but you can change order by calling setSortKey().
If alerts for a notification's group should be handled by a different notification, call setGroupAlertBehavior(). For example, if you want only the summary of your group to make noise, all children in the group should have the group alert behavior GROUP_ALERT_SUMMARY. The other options are GROUP_ALERT_ALL and GROUP_ALERT_CHILDREN.
Set a group summary
On Android 7.0 (API level 24) and higher, the system automatically builds a summary for your group using snippets of text from each notification. The user can expand this notification to see each separate notification, as shown in figure 1. To support older versions, which cannot show a nested group of notifications, you must create an extra notification that acts as the summary. This appears as the only notification and the system hides all the others. So this summary should include a snippet from all the other notifications, which the user can tap to open your app.
Note: The behavior of the group summary may vary on some device types such as wearables. To ensure the best experience on all devices and versions, always include a group summary when you create a group.
To add a group summary, proceed as follows:
Create a new notification with a description of the group—often best done with the inbox-style notification.
Add the summary notification to the group by calling setGroup().
Specify that it should be used as the group summary by calling setGroupSummary(true).
For example:
//use constant ID for notification used as group summary
int SUMMARY_ID = 0;
String GROUP_KEY_WORK_EMAIL = "com.android.example.WORK_EMAIL";
Notification newMessageNotification1 =
new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notify_email_status)
.setContentTitle(emailObject1.getSummary())
.setContentText("You will not believe...")
.setGroup(GROUP_KEY_WORK_EMAIL)
.build();
Notification newMessageNotification2 =
new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notify_email_status)
.setContentTitle(emailObject2.getSummary())
.setContentText("Please join us to celebrate the...")
.setGroup(GROUP_KEY_WORK_EMAIL)
.build();
Notification summaryNotification =
new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setContentTitle(emailObject.getSummary())
//set content text to support devices running API level < 24
.setContentText("Two new messages")
.setSmallIcon(R.drawable.ic_notify_summary_status)
//build summary info into InboxStyle template
.setStyle(new NotificationCompat.InboxStyle()
.addLine("Alex Faarborg Check this out")
.addLine("Jeff Chang Launch Party")
.setBigContentTitle("2 new messages")
.setSummaryText("janedoe#example.com"))
//specify which group this notification belongs to
.setGroup(GROUP_KEY_WORK_EMAIL)
//set this notification as the summary for the group
.setGroupSummary(true)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(emailNotificationId1, newMessageNotification1);
notificationManager.notify(emailNotificationId2, newMessageNotification2);
notificationManager.notify(SUMMARY_ID, summaryNotification);
The summary notification ID should stay the same so that it is only posted once, and so you can update it later if the summary information changes (subsequent additions to the group should result in updating the existing summary).

Use below give code for your notification manager and increment the count whenever a new notification received.
mNotificationManager.notify(count, mBuilder.build());

Related

Not able to add same Users message in Same group of Android Nougat Push Notifications as whatsapp

Here I'm trying to show chat messages in groups like whatsapp does in Android 7.0 or more but they're not getting displayed like that. I'm sending local push notifications by getting chat messages from Node.js. In android, I'm using socket client to fetch them and sending push notifications to the other user if their apps are in background. Multiple messages are going in one group but when I try to create a new group when some one else send messages its adding in a same group.
It just updates the title of push notification as I'm doing here:
public static void bundledNotification(String message, String name, String uId) {
Context context = ApplicationClass.context();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
++numberOfBundled;
issuedMessages.add(message);
//Build and issue the group summary. Use inbox style so that all messages are displayed
NotificationCompat.Builder summaryBuilder = new NotificationCompat.Builder(context)
.setContentTitle(name)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setGroupSummary(true)
.setGroup(uId);
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle("Messages:");
for (CharSequence cs : issuedMessages) {
inboxStyle.addLine(cs);
}
summaryBuilder.setStyle(inboxStyle);
notificationManager.notify(NOTIFICATION_BUNDLED_BASE_ID, summaryBuilder.build());
//Pending Intent
Intent notificationIntent = new Intent(context, ChatMessageActivity.class);
notificationIntent.putExtra("uid", Integer.parseInt(uId));
notificationIntent.putExtra(context.getString(R.string.notify_id), Integer.parseInt(uId));
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack
stackBuilder.addParentStack(ChatMessageActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(notificationIntent);
PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
//issue the Bundled notification. Since there is a summary notification, this will only display
//on systems with Nougat or later
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(name)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(contentIntent)
.setGroupSummary(true)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(name))
.setGroup(uId);
//Each notification needs a unique request code, so that each pending intent is unique. It does not matter
//in this simple case, but is important if we need to take action on a specific notification, such as
//deleting a message
int requestCode = NOTIFICATION_BUNDLED_BASE_ID + numberOfBundled;
if (messagesMap.get(uId) != null) {
messagesMap.get(uId).add(message);
} else {
ArrayList<String> messageList = new ArrayList<String>();
messageList.add(message);
messagesMap.put(uId, messageList);
notificationManager.notify(NOTIFICATION_BUNDLED_BASE_ID + numberOfBundled, builder.build());
}
AppPreferences.setChatNotificationNumber(context, AppUtils.PUSH_CHATS_NOTIFICATION_NUMBER, requestCode);
NotificationCompat.Builder childBuilder = new NotificationCompat.Builder(context)
.setContentTitle(name)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(contentIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setGroup(uId);
notificationManager.notify(requestCode,
childBuilder.build());
}
From above code it's always creating a one more notification at first time and second time it starts adding messages into old notification. But when I'm trying to add old messages into the thread of same user it creates a new message under main group of notification. Thanks in advance.
Use same setGroup and notification(NOTIFICATION_BUNDLED_BASE_ID) id(group wise)
Context context = ApplicationClass.context();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
++numberOfBundled;
issuedMessages.add(message);
//Build and issue the group summary. Use inbox style so that all messages are displayed
NotificationCompat.Builder summaryBuilder = new NotificationCompat.Builder(context)
.setContentTitle(name)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setGroupSummary(true)
.setGroup(1001);
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle("Messages:");
for (CharSequence cs : issuedMessages) {
inboxStyle.addLine(cs);
}
summaryBuilder.setStyle(inboxStyle);
notificationManager.notify(1001, summaryBuilder.build());

How to group android notifications like whatsapp?

I don´t know how to group two or more notifications into only one and show a message like "You have two new messages".
Steps to be taken care from the below code.
NotificationCompat.Builder:contains the UI specification and action information
NotificationCompat.Builder.build() :used to create notification (Which returns Notification object)
Notification.InboxStyle: used to group the notifications belongs to same ID
NotificationManager.notify():to issue the notification.
Use the below code to create notification and group it. Include the function in a button click.
private final int NOTIFICATION_ID = 237;
private static int value = 0;
Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.push_notify_icon);
public void buttonClicked(View v)
{
value ++;
if(v.getId() == R.id.btnCreateNotify){
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Lanes");
builder.setContentText("Notification from Lanes"+value);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(bitmap);
builder.setAutoCancel(true);
inboxStyle.setBigContentTitle("Enter Content Text");
inboxStyle.addLine("hi events "+value);
builder.setStyle(inboxStyle);
nManager.notify("App Name",NOTIFICATION_ID,builder.build());
}
}
For separate notifications assign different NOTIFICATION_IDs..
For full logic please consider checking my answer.I used the logic with shared preferences and broadcast receiver as i needed to group each user message into single one and be in sight of active notifications.As only by targeting the api level 23 you can get active notifications,it did not help me at all.So i decided to write some slight logic.Check it here if you feel like to.
https://stackoverflow.com/a/38079241/6466619
You need to create the notification so that it can be updated with a notification ID by calling NotificationManager.notify(ID, notification).
The following steps need to be created to update the notification:
Update or create a NotificationCompat.Builder object
Build a Notification object from it
Issue the Notification with the same ID you used previously
An example taken from the android developer docs:
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText).setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is updated.
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
...
Also see the Android docs on Stacking Notifications
https://developer.android.com/training/wearables/notifications/stacks.html
You can stack all your notifications into a single group using the setGroup method and passing your groupId string as parameter.
builer.setGroup("GROUP ID STRING" ) ;
NotificationManager nManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Lanes");
builder.setGroup("GROUP_ID_STRING");
builder.setContentText("Notification from Lanes"+value);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(bitmap);
builder.setAutoCancel(true);
inboxStyle.setBigContentTitle("Enter Content Text");
inboxStyle.addLine("hi events "+value);
builder.setStyle(inboxStyle);
nManager.notify("App Name",NOTIFICATION_ID,builder.build());

Android:Modify Pending Notification's Content

I am trying to modify existing notifications in android.
What I have in my app
When a notification is already in system tray and another notification appears, the second one overwrites the first notification content.
What I am looking for
If second Notification arrives then instead of overwriting the first I need to change title to show 2 New Messages and go on incrementing as notifications arrive.
Code Implemented
Bitmap icon = BitmapFactory.decodeResource(ctx.getResources(),
R.drawable.icon);
Intent launchActivity = new Intent(ctx, CordovaApp.class);
launchActivity.putExtra("heading",newsHeader);
launchActivity.putExtra("content",newsText);
PendingIntent pi = PendingIntent.getActivity(ctx,0, launchActivity, PendingIntent.FLAG_NO_CREATE);
ParseAnalytics.trackAppOpened(launchActivity);
if(pi==null){
Log.d(TAG, "Pending Intenet is null.");
}else{
Log.d(TAG, "Pending Intenet is not null.");
}
Notification noti = new NotificationCompat.Builder(ctx)
.setContentTitle(newsHeader)
.setContentText(newsText)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(icon)
.setContentIntent(pi)
.setAutoCancel(true)
.build();
NotificationManager nm = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, noti);
Update
I implemented the solution mentioned below by #yogendra and now I am getting two separate notifications. Instead of getting stacked. Below is updated code
Notification noti = new NotificationCompat.Builder(ctx)
.setContentTitle(newsHeader)
.setContentText(newsText)
.setSmallIcon(R.drawable.icon)
.setGroup(GROUP_KEY_EMAILS)
.setLargeIcon(icon)
.setContentIntent(pi)
.setLights(Color.parseColor("green"), 5000, 5000)
.setAutoCancel(true)
.setPriority(2)
.setTicker("Notification from App")
.setGroupSummary(true)
.build();
NotificationManager nm = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
int timeSeconds = (int)System.currentTimeMillis()%Integer.MAX_VALUE;
Log.i(TAG,"Timing function called "+timeSeconds);
nm.notify(timeSeconds, noti);
See your code
nm.notify(0, noti);
where
notify(int id, Notification notification)
Here 0 is the ID of notification which is to be managed with respect to each notification. If you want to show a different notification your notification id should be unique each time. If you try to post a notification with the same notification id your previously displayed notification will be replaced with the latest notification.
Solution
Now you need to display a custom notification with a custom layout and update the counter each time .
Source code to create a Custom Notification.
create global variable in your class :
private int count = 0;
private ArrayList<String> notificationList = new ArrayList<String>();
private String GROUP_KEY_EMAILS = "email";
/call method createNotification when you need to create notification and pass message what you need to show on message./
private void createNotification(String notificationMassage) {
notificationList.add(notificationMassage);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
// Create builder
Builder summaryNotification = new NotificationCompat.Builder(this)
.setContentTitle(notificationList.size()+" new messages")
.setSmallIcon(R.drawable.settings)
.setLargeIcon(largeIcon)
.setGroup(GROUP_KEY_EMAILS)
.setGroupSummary(true)
.setAutoCancel(true);
// Create style
InboxStyle nStyle = new NotificationCompat.InboxStyle();
nStyle.setBigContentTitle(notificationList.size()+" new messages");
nStyle.setSummaryText("Summery Text...<you can set as blank>");
for (String Str : notificationList) {
nStyle.addLine(Str);
}
summaryNotification.setStyle(nStyle);
mNotificationManager.notify(0, summaryNotification.build());
count++;
}
/**
please clear notification array list after tap on notification.
*/
For more detail please refer below link:
https://developer.android.com/training/wearables/notifications/stacks.html#AddGroup
https://developer.android.com/training/wearables/notifications/stacks.html#AddGroup

Android: Multiple Notifications as single list in Status Bar

I am trying to Notify user based on some criteria. Multiple Notifications are being shown in Status Bar but I want to Group the notification in single notification and when user clicks in the Status Bar, I want to retrieve all notifications in that group. Is that possible? Or I have to maintain PendingIntents of those notifications? Any help will be appreciated. For example, if birthdays of two friends come on same day, then 2 notifications should be shown. I want to combine these notifications i.e. instead of 2 notifications in the status bar, I want one, when user clicks on it, it should have information about 2 notifications. Is it possible?
Please see the code below for displaying notifications.
public void displayNotification(BirthdayDetail detail)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle(detail.getContactName());
builder.setContentText(detail.getContactBirthDate());
Intent resultIntent = new Intent(this.context, NotificationView.class);
resultIntent.putExtra("name", detail.getContactName());
resultIntent.putExtra("birthdate", detail.getContactBDate());
resultIntent.putExtra("picture_path", detail.getPicturePath());
resultIntent.putExtra("isContact", detail.isFromContact());
resultIntent.putExtra("notificationId", notificationId);
if(detail.isFromContact())
{
resultIntent.putExtra("phone_number", detail.getPhoneNumber());
}
PendingIntent resultPendingIntent = PendingIntent.getActivity(this.context, requestCode++,
resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
notificationManager
= (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());
notificationId++;
}
When you need to issue a notification multiple times for the same type
of event, you should avoid making a completely new notification.
Instead, you should consider updating a previous notification, either
by changing some of its values or by adding to it, or both.
You can use something like:
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is
// updated.
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
Source: http://developer.android.com/training/notify-user/managing.html

How to send multiply push-notifications and show number of them

I have a server with some data and in my app I want to show this data via push-notification, so the problem is I didn't get how to cooperate notification number in status bar with my notifiсations. In my app I get notifications as ArrayList from my server. For each notification I should use a "Notification builder", in which I'll put notify fields like icon, name, desc etc, and at least I should call "NotificationManager.notify" for each of them, but how I can show that I've just gotten 3 messages for example in my status bar(one icon with indicator of 3, NOT 3 icons), and don't multiply a notification sound, but still show all of them when I open a status bar.
My code:
public void sendNotifications(ArrayList<Message> messages){
int notifyID = 0;
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
for(Message message:messages){
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
Resources res = getApplicationContext().getResources();
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, messages.media))
.setTicker("Got a new message")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(message.titile)
.setContentText(message.text);
Notification notification = builder.getNotification();
mNotificationManager.notify(notifyID, notification);
notifyID++;
}
}
UPD
For more understanding what i want to i've added an images
-pic1 When i send notifications - icon shows me how much i got
-pic2 When i opened a status bar it shows me all my notifies
It is possible to do that?
You cannot do that - Combine 3 notification into one.
Either you create a single notification combining all the notifications or like this only.
It is not necessary that you will get 3 notifications. You can get 1 or 2 also.
I don't see the issue here. If there are 3 notifications, you will see 3 icons in the status bar.
Each icon represents an entry in the pull down notification bar- having one icon represent multiple entries wouldn't really make sense.
Notification.Builder has method setNumber to set number of notifications. It's described in Notification docs in Updating notifications section.
You can use Big view notification.
Check here : Notifications
Notification Id must be a constant. If notification id is different it will show as different notifications. So your code must be like this, declare ID and count as field variable:
public static final int NOTIFICATION_ID = 1;
private int notificationCount = 1;
and change the method like this:
public void sendNotifications(ArrayList<Message> messages){
int notifyID = 0;
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
for(Message message:messages){
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(notificationIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent contentIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_CANCEL_CURRENT);
Resources res = getApplicationContext().getResources();
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, messages.media))
.setTicker("Got a new message")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(message.titile)
.setContentText(message.text);
.setNumber(notificationCount++);
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
Thanks

Categories

Resources