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
Related
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 send couple notifications to the user and I use different notification ID for creating and notifying them and only one icon appears for all notifications. Everything is perfect. However when I swipe status bar to see notifications, it shows separated notifications.
As you see in the image I have two separated notifications, while I like to show them like telegram does (2 new messages). Does Android have something for that or I have to use a check previous notified messages and count unread notifications and show it as ContentText.
This is my code:
private final String GROUP_HEALTH = "HEALTH";
Random random = new Random();
int randInt = random.nextInt(9999 - 1000) + 1000;
int mNotificationId = randInt;
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext, 0,intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker(mContext.getString(R.string.app_name))
.setContentTitle(title)
.setContentText(message)
.setContentIntent(resultPendingIntent)
.setGroup(GROUP_HEALTH)
.setContentInfo(notifType);
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, mBuilder.build());
i guess every time this code runs, it generates random ID for every notification, use constant ID.
int mNotificationId = 1;
And yes, you should check for unread messages, and show that count by yourself.
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
I have a problem. What I want to do is, I just want to display a message in notification bar at frequent time of interval. For that I used two notification methods they are:
Notification notification = new Notification(icon, message, when);
......
notification.setLatestEventInfo(context, title, subTitle, intent);
Currently I am using API level 19. So I came to know above ones are deprecated. I was suggested to use Notification.builder. But after using that I am not getting proper output. Can anyone show me the code how to use Notification.Builder for above 2 statements...
Any help will be appreciated.
you can use this...
public static void createNotification(Context context, Long data) {
Random rnd = new Random();
int i = rnd.nextInt();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.app_icon)
.setContentTitle("Logo").setContentText("text");
mBuilder.setAutoCancel(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, activity.class);
resultIntent.putExtra(StringUtils.SESSIONID, data);
// The stack builder object will contain an artificial back stack for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(activity.class);
// stackBuilder.editIntentAt(index);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(i, mBuilder.build());
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setSubText(subTitle)
.setContentIntent(pendingIntent)
.build();
This is example is from here: Notification.Builder
To set the time you could use the method setWhen(long timestamp);
I tried to use the Notification.Builder and the Notification classes.
I tried using this code :
Notification notification = new Notification.Builder(this).build();
notification.icon = R.drawable.ic_launcher;
notification.notify();
but it seems useless.
I only want my app's icon to be added next to the battery icon,wifi icon and 3g icons.. Any way to do that? I appreciate your help.
You have to call the method build() after you have finished describing your notification. Check out the Android reference for an example.
Basically, you have to change your code to the following:
Context context = getApplicationContext();
NotificationCompat.Builder builder = new NotificationCompat.Builder(context )
.setSmallIcon(R.drawable.ic_launcher);
Intent intent = new Intent( context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, mID , intent, 0);
builder.setContentIntent(pIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = builder.build();
mNotificationManager.notify(mID, notif);
Note: this code will only allow to show your icon in the notification bar. If you want it to persist there, you will have to use FLAG_ONGOING_EVENT
You can add your app icon for status bar notification. Try this one
Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher).build();