I have a some troubles with understanding of goal of setGroup() method.
As docs said :
...Grouped notifications may display in a cluster or stack on devices which support such rendering....
Here it is the first question :
What it is this rendering? What's so special about it?!
I create a method which show a custom text message :
public static void showNotification(Context context, String title, String message, PendingIntent pendingIntent) {
notificationMessages.add(message);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
// .setGroupSummary(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentInfo("" + (notificationMessages.size()))
/*.setGroup(++i + "")*/;
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(title);
for (int i = 0; i < notificationMessages.size(); i++) {
inboxStyle.addLine(notificationMessages.get(i));
}
builder.setContentIntent(pendingIntent);
builder.setStyle(inboxStyle);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = builder.build();
mNotificationManager.notify(0, notification);
}
and play with notificationID, setGroup and setGroupSummary methods.
public static void showNotification(Context context, String title, String message, PendingIntent pendingIntent) {
notificationMessages.add(message);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
// .setGroupSummary(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentInfo("" + (notificationMessages.size()))
.setGroup(GROUP_KEY);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(title);
for (int i = 0; i < notificationMessages.size(); i++) {
inboxStyle.addLine(notificationMessages.get(i));
}
builder.setContentIntent(pendingIntent);
builder.setStyle(inboxStyle);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = builder.build();
mNotificationManager.notify(new Random().nextInt(3), notification);
}
But, no visual changes
comes if I commented lines or not. So here is a stuck for me in understanding of purpose of this method.
from the official docs:
http://developer.android.com/preview/features/notification-updates.html
Android N also allows you to bundle similar notifications to appear as a single notification. To make this possible, Android N uses the existing NotificationCompat.Builder.setGroup() method. Users can expand each of the notifications, and perform actions such as reply and dismiss on each of the notifications, individually from the notification shade.
Meaning the setGroup will only make a difference if the device supports it.
Devices that support it are:
Android Wear devices. when showing remote notifications, you can group together them
Android N. Devices running the Android N developer preview (or in the future the official N release), will show a group of notifications together
The following blog post shows how those work on Android N: https://medium.com/exploring-android/android-n-introducing-upgraded-notifications-d4dd98a7ca92
bellow is a render of that a group looks like:
That means that setGroup will make no difference on devices running anything bellow API23, that includes, Marshamallow, Lollipop, KitKat, etc.
setGroupSummaryis there to support grouped notifications on devices before Nougat. It replaces the single notifications with 1 summary notification.
On Nougat+ the system creates a normal group, which is not your notification with setGroupSummary(true)
Related
I am trying to implement bundled notification. After going through lots of tutorials and blogs, I got to know that I have to generate two notifications. One is regular notification, another one is summary notification. I followed everything as stated on those blog posts. Everything seems to work. But I get double notification sound for each notification on Android O. I am not able to fix this issue anyway. I have searched for any similar issue that other people might have faced. But I haven't found anything helpful.
Below are some code snippet of generating notification
Regular Notification
public Notification getSmallNotification(String channelId, String title, String body, Intent intent) {
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
ID_SMALL_NOTIFICATION,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, channelId);
builder.setTicker(title)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(resultPendingIntent)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_gw_notification)
.setColor(ContextCompat.getColor(mContext, R.color.color_bg_splash))
.setGroup(channelId);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
builder.setDefaults(Notification.DEFAULT_SOUND);
}
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
return notification;
}
Summary Notification
public Notification getSummaryNotification(String channelId, String title, String body) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, channelId)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_gw_notification)
.setColor(ContextCompat.getColor(mContext, R.color.color_bg_splash))
.setShowWhen(true)
.setGroup(channelId)
.setGroupSummary(true);
return builder.build();
}
Then I call this two functions simultaneously
notification = gwNotificationManager.getSmallNotification(channelId, title, body, intent);
notificationUtils.getManager().notify(channelId, (int) uniqueId, notification);
Notification summaryNotification = gwNotificationManager.getSummaryNotification(channelId, groupTitle, groupBody);
notificationUtils.getManager().notify(channelId, 0, summaryNotification);
How can I resolve the double sound issue? Any help would be much appreciated!
Another solution is to set in the builder:
setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
See documentation
I have the same problem on Android 8+ and I solved it by creating additional channel with low importance:
manager.createNotificationChannel(new NotificationChannel(silentChannelId, name, NotificationManager.IMPORTANCE_LOW));
And then creating summary notification using this channel:
new NotificationCompat.Builder(context, silentChannelId)
I have followed the Xamarin walkthrough, and it's not working for me.
The code falls through this cleanly, but it never sends the notification.
It never shows up on my emulator or device.
I have no idea what is going on.
public override void OnReceive(Context context, Intent intent)
{
string message = intent.GetStringExtra("message");
string title = intent.GetStringExtra("title");
int id = int.Parse(intent.GetStringExtra("id"));
//Generate a notification with just short text and small icon
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.SetAutoCancel(true) // Dismiss from the notif. area when clicked
.SetContentTitle(title) // Set its title
.SetContentText(message); // The message to display.
NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
notificationManager.Notify(id, builder.Build());
Any help or links would be very helpful. I'm just completely lost; been working on this for about 14 hours now, and cannot find any help on the Google.
Answer to my inquiry: You must have an Icon set for notifications to be properly build and sent. Though, it won't send an error for not having one.
Short version: Needed to add
.SetSmallIcon(Resource.Drawable.icon);
Add an icon to notification.
Notification.Builder builder = new Notification.Builder (this)
.SetContentTitle ("Title")
.SetContentText ("Message")
.SetSmallIcon (Resource.Drawable.ic_notification);
Notification notification = builder.Build();
NotificationManager notificationManager =
GetSystemService (Context.NotificationService) as NotificationManager;
const int notificationId = 0;
notificationManager.Notify (notificationId, notification);
I wrote the below method for showing FCM notification on my android 5.1 device. When I run the code inside a FirebaseMessagingService it is just giving single line notification , where if I run the same code inside my Activity its giving expandable notifications.
I basically need my long FCM text notifications to get expanded on notifications rather than showing partial notification text.
Any leads?
private void showNotif(String messageBody){
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
// Constructs the Builder object.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
.setAutoCancel(true)
.setContentIntent(pendingIntent)
/*
* Sets the big view "big text" style and supplies the
* text (the user's reminder message) that will be displayed
* in the detail area of the expanded notification.
* These calls are ignored by the support library for
* pre-4.1 devices.
*/
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody));
// android.support.v4.app.NotificationManagerCompat mNotifManager = (NotificationManagerCompat) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());
}
This should work .
Big Text notifcations are shown in normal mode when there are other notifications on top . Try to expand it while testing.
You need to creare notification using this method https://fcm.googleapis.com/fcm/send and not using firebase console and all would be ok
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());
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());