for some reason whenever I send a notification the notification bubble does not show up. Ive allowed notification bubbles from the developer options and compileSdkVersion is 29. Bubble activity just has a button in it for testing purposes. Any help will be greatly appreciated.
My code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NotificationManager notificationManager = mContext.getSystemService(NotificationManager.class);
// set up notification channel
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(CHANNEL_DESCRIPTION);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
// create person
Person person = new Person.Builder()
.setName("Notification")
.setIcon(Icon.createWithResource(mContext, R.drawable.ic_notification))
.setBot(true)
.setImportant(true)
.build();
// create bubble meta data
Intent target = new Intent(mContext, BubbleActivity.class);
PendingIntent bubbleIntent = PendingIntent.getActivity(mContext, 0, target, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.BubbleMetadata bubbleMetadata = new Notification.BubbleMetadata.Builder()
.setDesiredHeight(300)
.setIcon(Icon.createWithResource(mContext, R.drawable.ic_notification))
.setSuppressNotification(true)
.setAutoExpandBubble(false)
.setIntent(bubbleIntent)
.build();
// create message style
Notification.MessagingStyle style = new Notification.MessagingStyle(person)
.setGroupConversation(false)
.addMessage("notification", currentTimeMillis(), person);
// create notification intent
Intent target2 = new Intent(mContext.getApplicationContext(), LaunchActivity.class);
PendingIntent notificationIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 1, target2, PendingIntent.FLAG_UPDATE_CURRENT);
// create notification
Notification notification = new Notification.Builder(mContext, CHANNEL_ID)
.setContentTitle("Notification")
.setSmallIcon(Icon.createWithResource(mContext, R.drawable.ic_notification))
.setLargeIcon(Icon.createWithResource(mContext, R.drawable.ic_notification))
.setCategory(Notification.CATEGORY_MESSAGE)
.setStyle(style)
.setBubbleMetadata(bubbleMetadata)
.addPerson(person)
.setShowWhen(true)
.setContentIntent(notificationIntent)
.build();
if (notificationManager != null) {
notificationManager.notify(0, notification);
}
}
You need to set a shortcut ID on the notification. Once that is done, your notifications will appear in the conversation space and will be allowed to bubble. Note though that bubbles will not initially bubble automatically. It is up to the user to invoke/trigger this.
Please the following resources:
https://developer.android.com/guide/topics/ui/conversations#api-shortcuts
https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setShortcutId(java.lang.String)
Related
I write this code to show a notification in android. But this notification is only shown in the status bar. I want when a message received show notifications on the top screen like telegram app:
enter image description here
My code:
NotificationManager mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String offerChannelId = "offerChannelId";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String offerChannelName = "offerChannelName";
String offerChannelDescription = "offerChannelDescription";
int offerChannelImportance = NotificationManager.IMPORTANCE_HIGH;
#SuppressLint("WrongConstant") NotificationChannel notifChannel = new NotificationChannel(offerChannelId, offerChannelName, offerChannelImportance);
notifChannel.setDescription(offerChannelDescription);
mNotifyManager.createNotificationChannel(notifChannel);
}
NotificationCompat.Builder sNotifBuilder = new NotificationCompat.Builder(getBaseContext(), offerChannelId);
sNotifBuilder.setSmallIcon(R.drawable.ic_notifications)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notifications))
.setColor(getResources().getColor(R.color.baseColor_yellow))
.setContentTitle("title")
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_MAX);
mNotifyManager.notify(1, sNotifBuilder.build());
How I do it?
Min SDK is 21.
Thanks in advance.
I found a solution for you. Hope it may help you.
//build notification
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Ping Notification")
.setContentText("Tomorrow will be your birthday.")
.setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
.setPriority(NotificationCompat.PRIORITY_HIGH) //must give priority to High, Max which will considered as heads-up notification
.addAction(R.drawable.dismiss, getString(R.string.dismiss), piDismiss)
.addAction(R.drawable.snooze, getString(R.string.snooze), piSnooze);
//set intents and pending intents to call service on click of "dismiss" action button of notification
Intent dismissIntent = new Intent(this, MyService.class);
dismissIntent.setAction(ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
//set intents and pending intents to call service on click of "snooze" action button of notification
Intent snoozeIntent = new Intent(this, MyService.class);
snoozeIntent.setAction(ACTION_SNOOZE);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
// Gets an instance of the NotificationManager service
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* Notification for oreo*/
String channelId = "channel-01";
String channelName = "Demo";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
//to post your notification to the notification bar with a id. If a notification with same id already exists, it will get replaced with updated information.
notificationManager.notify(0, builder.build());
Minimum SDK is Lolipop.
I am working on an app where i am using custom Push Notification whenever there is an update from server that we need to send the notification, i am sending the notification using Notification builder and everything is working as expected, and i am redirecting the user to the relevant post on the ViewPager by mapping the Heading of the Notification.
I am attaching the code i am using
Notification Builder code
Intent resultIntentArticle = new Intent(context, HomeActivity.class);
resultIntentArticle.putExtra("pushNotificationClick", "yes");
resultIntentArticle.putExtra("heading", allArticles.get(0).getArticleHeading().trim());
resultIntentArticle.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
0, resultIntentArticle,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(context);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(R.mipmap.icon_not);
} else {
mBuilder.setSmallIcon(R.mipmap.icon_not);
}
mBuilder.setColor(getResources().getColor(R.color.colorPrimary));
mBuilder.setContentTitle("" + allArticles.get(0).getArticleHeading().trim())
.setContentText("" + allArticles.get(0).getArticleContent().trim())
.setAutoCancel(true)
.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableLights(true);
assert mNotificationManager != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify((int) System.currentTimeMillis() /* Request Code */, mBuilder.build());
currentNotificationStatus = "sent";
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("currentNotificationStatus" +
"", "" + currentNotificationStatus).apply();
I am sending two variables with PendingIntent i.e. pushNotificationClick and heading and am recieving it inside my Activity like this.
notificationClickedStatus = getIntent().getStringExtra("pushNotificationClick");
notificationHeading = getIntent().getStringExtra("heading");
Now the problem is that whenever we get 2-3 notifications and the user clicked on the very first notification that i have got, i am still getting the latest Notification heading in my activity. Earlier it was working completely fine, but now i am not getting any clue.
I am trying to group notifications and trigger sounds only for some of them using notification builder setSound() method, but it doesn't work. Each time I receive notifications it triggers the ringtone even though I call setSound(null)
This is my code:
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getContext());
stackBuilder.addParentStack(getParentActivityClass());
Intent notificationIntent = intent == null ? new Intent() : new Intent(intent);
if (cls != null)
notificationIntent.setClass(getContext(), cls);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
stackBuilder.addNextIntentWithParentStack(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
InboxStyle style = new NotificationCompat.InboxStyle();
int mapId = subGroupId + groupId;
putGroupLine(mapId, text);
List<String> notifLines = groupedNotificationsMap.get(mapId);
for (int i = 0; i < notifLines.size(); i++) {
style.addLine(notifLines.get(i));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = "default";
String channelName = "Default";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName
, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
if (alert == false) {
chan.setSound(null, null);
chan.setVibrationPattern(null);
}
else {
chan.setVibrationPattern(vibrate);
}
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(chan);
}
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(getSmallIconResource())
.setAutoCancel(true);
int colorRes = getSmallIconColor();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
}
if (alert) {
mBuilder.setSound(getRingtone());
mBuilder.setVibrate( vibrate );
}
else {
mBuilder.setSound(null);
mBuilder.setVibrate(null);
}
Notification notif = mBuilder
.setContentTitle(title)
.setTicker(text)
.setContentText(text)
.setSmallIcon(getSmallIconResource())
.setStyle(style
.setBigContentTitle(title)
)
.setGroup("g" + groupId)
.setContentIntent(pendingIntent)
.build();
NotificationCompat.Builder summaryBiulder = new NotificationCompat.Builder(getContext(), "default")
.setContentTitle(title)
.setAutoCancel(true)
//set content text to support devices running API level < 24
.setContentText(text)
.setSmallIcon(getSmallIconResource())
//build summary info into InboxStyle template
.setStyle(new InboxStyle()
.setBigContentTitle(title)
.setSummaryText(title))
.setColor(colorRes)
//specify which group this notification belongs to
.setGroup("g" + groupId)
//set this notification as the summary for the group
.setGroupSummary(true)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
.setContentIntent(pendingIntent);
if (alert) {
summaryBiulder.setSound(getRingtone());
summaryBiulder.setVibrate( vibrate );
}
else {
summaryBiulder.setSound(null);
summaryBiulder.setVibrate(null);
}
Notification summaryNotification = summaryBiulder .build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.flags |= Notification.FLAG_HIGH_PRIORITY;
notifManager.notify(subGroupId, notif);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notifManager.notify(groupId, summaryNotification);
}
Any suggestions?
Your problem is about notification importance
importance types
IMPORTANCE_MAX: unused
IMPORTANCE_HIGH: shows everywhere, makes noise and peeks
IMPORTANCE_DEFAULT: shows everywhere, makes noise, but does not visually intrude
IMPORTANCE_LOW: shows everywhere, but is not intrusive
IMPORTANCE_MIN: only shows in the shade, below the fold
IMPORTANCE_NONE: a notification with no importance; does not show in the shade
source
Although the other answers are useful, the main issue here was that the notification channel was already created. So, as stated in the docs, the behavior of a channel cannot be changed after creation (sound and vibration in this case). Only name and description can be changed, the user has full control over the rest.
In the code snippet,
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName,
NotificationManager.IMPORTANCE_HIGH);
Try replacing
NotificationManager.IMPORTANCE_HIGH to NotificationManager.IMPORTANCE_NONE
As according to Android developer documentation,
IMPORTANCE_HIGH
Higher notification importance: shows everywhere, makes noise and peeks. May use full screen intents.
So it may be making sound due to this.
Here's the link to other importance values available
I am generating local notification with multiple lines. All lines are showing properly but contentTitle and contentText are not showing.
Here is my code to generate a notification:
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
int num = (int) System.currentTimeMillis();
PendingIntent pendingIntent = stackBuilder.getPendingIntent(num, PendingIntent.FLAG_UPDATE_CURRENT);
String id = "notification_channel_id";
CharSequence name = "Message_Notification";
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, id)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title")
.setContentText("time")
.setAutoCancel(true)
.setGroupSummary(true)
.setGroup(GROUP_KEY)
.setContentIntent(pendingIntent)
.setChannelId(id);
if (subTitle != null) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle("Dose Reminder");
if (subTitle.contains("---")) {
String[] splitStrings = subTitle.split("---");
for (int i = 0; i < splitStrings.length; i++) {
inboxStyle.addLine(splitStrings[i]);
}
} else {
inboxStyle.addLine(subTitle);
// Moves the expanded layout object into the notification object.
notificationBuilder.setStyle(inboxStyle);
}
// Moves the expanded layout object into the notification object.
notificationBuilder.setStyle(inboxStyle);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setColor(ContextCompat.getColor(context, R.color.colorAccent));
} else {
notificationBuilder.setLargeIcon(bm);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// The user.-visible description of the channel.
String description = "Notifications contains messages which was sent by dev team.";
int importance = NotificationManager.IMPORTANCE_MAX;
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
if (notificationManager != null) {
notificationManager.createNotificationChannel(mChannel);
}
}
// Sets an ID for the notification
// Gets an instance of the NotificationManager service
final NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
if (mNotifyMgr != null) {
mNotifyMgr.notify(num, notificationBuilder.build());
}
When notification comes "title" and "time" are not showing. It showing "Dose Reminder" and subTitles in multiple lines.
Am I missing something?
setBigContentTitle(CharSequence title)
Overrides ContentTitle in the big form of the template.
https://developer.android.com/reference/android/app/Notification.InboxStyle
Check Use MessagingStyle section
https://developer.android.com/training/notify-user/build-notification
JFYI by default timestamp is gone in push notifications, Android 7 (Nougat) onwards
Having trouble sending stacked notifications using setGroup. The moment I invoke setGroup no notifications are being sent on the device or the Android Wear emulator. Some sample code...
Intent intent1 = new Intent(this, AddActivity.class);
PendingIntent pIntent1 = PendingIntent.getActivity(this, 0, intent1, 0);
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);
nBuilder.setContentTitle("Fence Monitor").setContentText("FENCE " + status).setSmallIcon(R.drawable.ic_launcher).setContentIntent(pIntent1);
NotificationCompat.Builder nBuilder1 = new NotificationCompat.Builder(this);
Notification secondNotification = nBuilder1.setContentTitle("Fence Monitor").setContentText("This is additional information related to this notification").setSmallIcon(R.drawable.ic_launcher).build();
WearableNotifications.Action.Builder aBuilder = new WearableNotifications.Action.Builder(android.R.drawable.ic_input_add,"Add Content",pIntent1);
WearableNotifications.Action action = aBuilder.build();
RemoteInput.Builder rBuilder = new RemoteInput.Builder(QUICK_REPLY);
RemoteInput rInput = rBuilder.setAllowFreeFormInput(true).setLabel("QUICK REPLY").build();
WearableNotifications.Builder wBuilder = new WearableNotifications.Builder(nBuilder);
Notification notification = wBuilder.setGroup(FENCE_NOTIFICATIONS_GROUP,order).addAction(action).addPage(secondNotification).addRemoteInputForContentIntent(rInput).build();
//Notification notification = wBuilder.setGroup(FENCE_NOTIFICATIONS_GROUP,order).build();
NotificationManagerCompat nManager = NotificationManagerCompat.from(this);
int notificationId = (new Random()).nextInt();
Log.d("Notification Id",""+notificationId);
nManager.notify(notificationId, notification);
I was playing around with stacked notifications and realized that having a summary notification is needed for your notification to show up (at-least in my case it was). The android documentation: https://developer.android.com/wear/notifications/stacks.html#AddSummary mentions that is important but doesn't say it is required.
Either ways, try this and see if it works. I was able to get your code to work by adding a summary notification.
/**
* Create a summary notification
*/
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.alert_dialog_icon);
WearableNotifications.Builder wearableBuilder = new WearableNotifications
.Builder(builder)
.setGroup(FENCE_NOTIFICATIONS_GROUP,
WearableNotifications.GROUP_ORDER_SUMMARY);
Notification summaryNotification = wearableBuilder.build();
/**
* Notify. First publish the summary notification and then send out the
* other multi-page notification.
*/
NotificationManagerCompat nManager = NotificationManagerCompat.from(this);
int notificationId = (new Random()).nextInt();
Log.d("Notification Id",""+notificationId);
nManager.notify(notificationId, summaryNotification);
notificationId = (new Random()).nextInt();
Log.d("Notification Id",""+notificationId);
nManager.notify(notificationId, notification);
The WearableNotificationsSample included in the Android Wear Developer Preview shows how you can build stacked notifications:
public Notification[] buildNotifications(Context context, BuildOptions options) {
NotificationCompat.Builder childBuilder1 = new NotificationCompat.Builder(context)
.setContentTitle(context.getString(R.string.first_child_content_title))
.setContentText(context.getString(R.string.first_child_content_text));
Notification child1 = new WearableNotifications.Builder(childBuilder1)
.setGroup(EXAMPLE_GROUP_KEY, 0)
.build();
NotificationCompat.Builder childBuilder2 = new NotificationCompat.Builder(context)
.setContentTitle(context.getString(R.string.second_child_content_title))
.setContentText(context.getString(R.string.second_child_content_text))
.addAction(R.mipmap.ic_app_notification_studio,
context.getString(R.string.second_child_action),
NotificationUtil.getExamplePendingIntent(
context, R.string.second_child_action_clicked));
Notification child2 = new WearableNotifications.Builder(childBuilder2)
.setGroup(EXAMPLE_GROUP_KEY, 1)
.build();
Notification summary = buildBasicNotification(context, options)
.setGroup(EXAMPLE_GROUP_KEY, WearableNotifications.GROUP_ORDER_SUMMARY)
.build();
return new Notification[] { summary, child1, child2 };
}
Just recently I did a blog post which had a complete example that you might want to try out: http://android-developers.blogspot.com/2014/05/stacking-notifications-for-android-wear.html
Bitmap bitmapMila = BitmapFactory.decodeResource(getResources(), R.drawable.mila128);
// Nuke all previous notifications and generate unique ids
NotificationManagerCompat.from(this).cancelAll();
int notificationId = 0;
// String to represent the group all the notifications will be a part of
final String GROUP_KEY_MESSAGES = "group_key_messages";
// Group notification that will be visible on the phone
NotificationCompat.Builder builderG = new NotificationCompat.Builder(this)
.setContentTitle("2 Pet Notifications")
.setContentText("Mila and Dylan both sent messages")
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(bitmapMila);
Notification summaryNotification = new WearableNotifications.Builder(builderG)
.setGroup(GROUP_KEY_MESSAGES, WearableNotifications.GROUP_ORDER_SUMMARY)
.build();
// Separate notifications that will be visible on the watch
Intent viewIntent1 = new Intent(this, MainActivity.class);
PendingIntent viewPendingIntent1 =
PendingIntent.getActivity(this, notificationId+1, viewIntent1, 0);
NotificationCompat.Builder builder1 = new NotificationCompat.Builder(this)
.addAction(R.drawable.ic_action_done, "Treat Fed", viewPendingIntent1)
.setContentTitle("Message from Mila")
.setContentText("What's for dinner? "
+ "Can we have steak?")
.setSmallIcon(R.drawable.ic_launcher);
Notification notification1 = new WearableNotifications.Builder(builder1)
.setGroup(GROUP_KEY_MESSAGES)
.build();
Intent viewIntent2 = new Intent(this, MainActivity.class);
PendingIntent viewPendingIntent2 =
PendingIntent.getActivity(this, notificationId+2, viewIntent2, 0);
NotificationCompat.Builder builder2 = new NotificationCompat.Builder(this)
.addAction(R.drawable.ic_action_done, "Water Filled", viewPendingIntent2)
.setContentTitle("Message from Dylan")
.setContentText("Can you refill our water bowl?")
.setSmallIcon(R.drawable.ic_launcher);
Notification notification2 = new WearableNotifications.Builder(builder2)
.setGroup(GROUP_KEY_MESSAGES)
.build();
// Issue the group notification
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId+0, summaryNotification);
// Issue the separate wear notifications
notificationManager.notify(notificationId+2, notification2);
notificationManager.notify(notificationId+1, notification1);