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
Related
Step1 : Build Notification with Reply intent and heads up notification
private void buildInlineReplyNotification() {
// Create an instance of RemoteInput.Builder that you can add to your notification action.
// This class's constructor accepts a string that the system uses as the key for the text input.
// Later, your handheld app uses that key to retrieve the text of the input.
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(
getResources().getString(R.string.reply_label)).build();
// Attach the RemoteInput object to an action using addRemoteInput().
NotificationCompat.Action compatAction =
new NotificationCompat.Action.Builder(R.mipmap.ic_reply,
getResources().getString(R.string.reply), replyPendingIntent).addRemoteInput(
remoteInput).setAllowGeneratedReplies(true).build();
// Build the notification and add the action.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_notification)
.setContentTitle(
getResources().getString(R.string.notification_created) + mNotificationId)
.setContentText(getResources().getString(R.string.type_reply))
.setShowWhen(true)
.addAction(compatAction);
mBuilder.setPriority(Notification.PRIORITY_HIGH).setVibrate(new long[0]);
// Issue the notification.
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(mNotificationId, mBuilder.build());
}
Step2 : cancel after reply from notification
private void updateNotification(Context context, int notifyId) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_notification)
.setContentText(context.getString(R.string.message_sent));
notificationManager.cancel(notifyId);
}
Issues is not cancel notification by notificationManager.cancel(notifyId) but if i remove this mBuilder.setPriority(Notification.PRIORITY_HIGH).setVibrate(new long[0]); Than work perfect so, what is issue with priority in notification ?
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());
I want to show notifications like on picture. If there is more than one, I want to show a counter too. I didn't find info in official doc. Now I just update my notification by id:
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
.notify(PUSH_NOTIFICATION_ID, notification);
How can I do it ?
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(topic);
mBuilder.setContentText(new String(message.getPayload()));
mBuilder.setAutoCancel(true);
mBuilder.mNumber = 1;//get your number of notification from where you have save notification
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(notify_id, mBuilder.build());
To create a stack, call setGroup() for each notification you want in the stack and specify a group key.
final static String GROUP_KEY_EMAILS = "group_key_emails";
// Build the notification, setting the group appropriately
Notification notif = new NotificationCompat.Builder(mContext)
.setContentTitle("New mail from " + sender1)
.setContentText(subject1)
.setSmallIcon(R.drawable.new_mail)
.setGroup(GROUP_KEY_EMAILS)
.build();
// Issue the notification
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(notificationId1, notif);
Reference: https://developer.android.com/training/wearables/notifications/stacks.html
As Richard said in this question > Possible to continuously update text in the notification area? , I have the same issue here .
I want to update text in the notification area .
This question is answered and accepted , but the answer doesn't help me .
It's about to create text as bitmap dynamically and set it to Small Icon of notification .
But as Richard commented , the images for setSmallIcon must be predefined in the package.There is no ability to edit them on the fly.
Please kindly show me the right way to do this stuff .
It's quite simple to update your Notification.
First of all when you create it you must create it with an id.
NotificationManager 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("Title")
.setContentText("Text")
.setSmallIcon(R.drawable.ic_notify);
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
Now to update your Notification you only need to notify the new notification with the old id and this will be updated (you don't need to reset the paraneter you don't want to update).
mNotifyBuilder.setContentText(setContentText("New Text")
mNotifyBuilder.setSmallIcon(R.drawable.ic_new_notify);
//this update your notification
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
I tried to make one but it has one disadvantage is that, it has one empty notification in notification drawer,
public static int when = 0;
private void generateNotification(Context context) {
Log.i(TAG, "generateNotification");
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(
this.getApplicationContext(), 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotification = new NotificationCompat.Builder(
this)
// .setContentTitle("AppName")
// .setContentText("Message For Notification Drawer")
// .setSound(soundUri)
// .setDefaults(Notification.DEFAULT_SOUND)
// .setVibrate(new long[] { 1000, 1000 })
// .addAction(R.drawable.ic_launcher, "View", pIntent)
// .addAction(0, "Remind", pIntent)
// .setNumber(fCount)
// .setWhen(when)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker(Integer.toString(when)) // Set String you want
.setAutoCancel(true)
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// notificationManager.notify(when, mNotification.build());
notificationManager.notify(1, mNotification.build());
when++;
}
I need to implement expand and collapse notification in status bar for android 4.0 and above version. I have search on google for this but didn't getting any code solution for implementation does anybody have I idea how to implement this
Thank You in advance
An expandable Notification is a special case of a Notification Big View. If the Big View is not at the top of the notification drawer, it it shown 'closed' and is expandable by swipe. Quote from Android Developers:
A notification's big view appears only when the notification is expanded, which happens when the notification is at the top of the notification drawer, or when the user expands the notification with a gesture. Expanded notifications are available starting with Android 4.1.
The Big View Notification can be created as follows:
Notification notification = new Notification.BigTextStyle(builder)
.bigText(myText).build();
or
Notification notification = new Notification.BigPictureStyle(builder)
.bigPicture(
BitmapFactory.decodeResource(getResources(),
R.drawable.my_picture)).build();
Here is a tutorial.
Notification noti = new Notification.Builder()
... // The same notification properties as the others
.setStyle(new Notification.BigPictureStyle().bigPicture(mBitmap))
.build();
You change
.setStyle(new NotificationCompat.BigTextStyle().bigText(th_alert))
along with the announcement OK !!!
notification = new NotificationCompat.Builder(context)
Here is an example:
Expandable Notifications and Notifications Groups
You can set Code
Intent intent = new Intent(context, ReserveStatusActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
intent = new Intent(String.valueOf(PushActivity.class));
intent.putExtra("message", MESSAGE);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(PushActivity.class);
stackBuilder.addNextIntent(intent);
// PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// android.support.v4.app.NotificationCompat.BigTextStyle bigStyle = new NotificationCompat.BigTextStyle();
// bigStyle.bigText((CharSequence) context);
notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(th_title)
.setContentText(th_alert)
.setAutoCancel(true)
// .setStyle(new Notification.BigTextStyle().bigText(th_alert) ตัวเก่า
// .setStyle(new NotificationCompat.BigTextStyle().bigText(th_title))
.setStyle(new NotificationCompat.BigTextStyle().bigText(th_alert))
.setContentIntent(pendingIntent)
.setNumber(++numMessages)
.build();
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager.notify(1000, notification);
or
private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
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);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
// .setContentTitle(notification.getTitle())
.setContentTitle(getResources().getText(R.string.app_name))
.setContentText(notification.getBody())
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(notification.getBody()))
.setContentInfo(notification.getTitle())
.setLargeIcon(icon)
.setColor(Color.RED)
.setSmallIcon(R.drawable.logo);
try {
String picture_url = data.get("picture_url");
if (picture_url != null && !"".equals(picture_url)) {
URL url = new URL(picture_url);
Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
notificationBuilder.setStyle(
new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
);
}
} catch (IOException e) {
e.printStackTrace();
}
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.YELLOW, 1000, 300);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
27/07/2021 :
You should can read detail this : Expandable Notifications and Notifications Groups
I Couldn't able to set new instance of new NotificationCompat.BigTextStyle() in .setStyle() method of Notification. So I have used the below one, new instance of new Notification.BigTextStyle() in .setStyle().
Notification builder =new Notification.Builder(this)
.setSmallIcon(Notification_icons[icon])
.setContentTitle(title)
.setContentText(description)
.setChannelId(channelID_Default)
.setOngoing(true)
.setStyle(new Notification.BigTextStyle()
.bigText(description))
.build();
There is a method for this function you can show a small icon when notification collapsed and show a large one when a notification expanded.
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.notification)
var notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.new_post)
.setContentTitle(imageTitle)
.setContentText(imageDescription)
.setLargeIcon(bitmap)
.setStyle(NotificationCompat.BigPictureStyle()
.bigPicture(bitmap)
.bigLargeIcon(null))
.build()
(2021) Stumbled upon this question when I was having issues with expanding my notification which had a larger text.
Solved by referring to the Android docs on Expandable Notifications: Create an Expandable Notification
Nimisha V's answer shows how to expand a large image on a notification. The below code is used for expanding large text on a notification.
var notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setContentTitle(notification_title)
.setContentText(notification_message)
.setStyle(NotificationCompat.BigTextStyle()
.bigText(notification_message))
.build()
We can't create expandable notification in below android 4.1 versions.
But Instead of this we can do that we can stacked the notifications and then we can set a pending intent to our pretty custom activity which shows all notification in list.
User will happy to see this :)