Force Grouping of Notifications? - android

According to the Notification Design Guidelines documentation:
If the same app sends four or more notifications and does not specify a grouping, the system automatically groups them together.
So I tested this out:
However, it only works when you have 4 or more notifications. I notice Messenger does this when you only have two notifications:
So my question is, can I tell the Android to always group my notifications like Messenger does? Or does Messenger use the setGroup() method that I would prefer not to use...

It's doable.
The concept is to make a group notification builder for grouping up notifications and apply same groupKey to other notification builder. And call NotificationManagerCompat.notify() to build group notification beforehand. So these notifications with same groupKey will group together.
You can add group notification builder with NotificationCompat.Builder.setGroup("GROUP_KEY") and NotificationCompat.Builder.setGroupSummary(true).
And add NotificationCompat.Builder.setGroup("GROUP_KEY") to other notifications.
val groupKey = "GROUP_KEY"
val groupBuilder = NotificationCompat.Builder(context, "CHANNEL_ID")
groupBuilder.apply {
setAutoCancel(true)
...
setGroupSummary(true)
setGroup(groupKey)
}
val builder = NotificationCompat.Builder(context, "CHANNEL_ID")
groupBuilder.apply {
setAutoCancel(true)
...
setGroup(groupKey)
}
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.notify(NOTIFICATION_ID, groupBuilder.build())
notificationManager.notify(NOTIFICATION_TAG, NOTIFICATION_ID, builder.build())

Related

FCM Push Notifications are only displayed when app is in background

I am using the following code to receive and display push notifications:
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.getNotification() != null) {
var title : String = remoteMessage.notification!!.title!!
var message : String = remoteMessage.notification!!.body!!
val intent = Intent(this, LoginCommonActivity::class.java)
intent.addflags(intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
var builder: NotificationCompat.Builder;
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//val notificationManager = NotificationManagerCompat.from(applicationContext)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel =
NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannels(notificationChannel)
builder = NotificationCompat.Builder(applicationContext, notificationChannel.id)
} else {
builder = NotificationCompat.Builder(applicationContext)
}
builder = builder.setSmallIcon(R.drawable.ic_app_logo_black)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setDefaults(Notification.DEFAULT_ALL)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000))
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
notificationManager.notify(System.currentTimeMillis().toInt(), builder.build())
}
}
But PNs' are only displayed when app is in background or closed. Debugging the FCMMessagingService, I can see that PNs' are being sent by the server and received in onMessageReceive(). It appears that the notify() method is not working, or something else in the code is failing.
As per this article, FCM notifications are handled by the internal Firebase service when the app is in background, else they are received in onMessageReceived() of FirebaseMessagingService when the app is in the foreground, and we have to manually display them with notify(). But this isn't working.
We've already seen this problem before here, here, here and here. But that was maybe when the old GCM features were still present in FCM. By this time FCM must have been completely overhauled.
My questions are:
What is the default protocol for handling push notifications if they arrive when the app is in the foreground?
Looking at other popular apps - WhatsApp, Google Pay, Zomato - I do not ever recall seeing a push notification when the app is in the foreground. Does this mean that push notifications never appear in the tray when the app is in the foreground?
If so, then what is the reason for having the NotificationManager.notify() function in the first place? If push notifications only appear when the app is in the background, and they are auto-handled by the Firebase service, then why is this method there at all? Is this just a relic of the old GCM library?
Can someone please point out where the problem is?
I will try to answer all your questions
First notification are of two types
1): Notification Payload ( Your's case)
2): Data Payload
1): Notification Payload
In notification payload
-If App in Background ( FCM will handle push notifications it self )
-If App in Foreground ( payload will receive in onMessageReceived we have to write our own logic to weather show notification or not )
2): Data Payload
In data payload
-If App in Background ( payload will receive in onMessageReceived we have to write our own logic to weather show notification or not )
-If App in Foreground ( payload will receive in onMessageReceived we have to write our own logic to weather show notification or not )
For Notification Please try using updated code from android guide using Compat library
https://developer.android.com/training/notify-user/build-notification#groovy
Just remove "notification" key from payload and provide only "data" key.
Application handles notification messages only if the app is in foreground but it handles data messages even if the application is in background or closed.
more info: https://stackoverflow.com/a/38850030/19892188

Push notification android basic questions

I am about it implement push notification from a node.js-server into my Android/kotlin-app.
Therefore i have used pusher.com which was very easy to implement for basic notifications
But: I want to create more costumizable notification, like a large image etc.
All the samples I find is about how to create a notification in Android.
e.g. this works great:
notificationManager = NotificationManagerCompat.from(this);
val largeIcon = BitmapFactory.decodeResource(resources, R.drawable.large)
val activityIntent = Intent(this, MainActivity::class.java)
val contentIntent = PendingIntent.getActivity(this, 0, activityIntent, 0)
val notification: Notification = NotificationCompat.Builder(this, App.CHANNEL_1_ID)
.setContentText("test")
.setContentTitle("test")
.setSmallIcon(R.drawable.heizungan)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setLargeIcon(largeIcon)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setStyle(NotificationCompat.BigTextStyle()
.bigText("test")
.setBigContentTitle("test")
.setSummaryText("Heizung"))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setColor(Color.RED)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.build()
notificationManager!!.notify(1, notification)
Using this in my app, i can create and show this notification.
But how do I push this?
How can I push some values to my device and then show this notification?
Thanks
You would need a cloud service to actually send the notification to your device.
An example would be Firebase Cloud Messaging
As milhamj has already said you can use Firebase Cloud Messaging
How to do this... (click)
Find my answer for android service
On this link you have php code on backend that you can rewrite in javascript or check this link for nodejs
and java code for Android app (MyFirebaseMessagingService)

Notification Group not working without summary

I am implementing notifications and want to group them for display in notification bar.
Currently I am implementing the example from
Create a Group of Notifications in Android's official developer documentation.
I implemented this method:
private void makeNotification()
{
createNotificationChannel();
int SUMMARY_ID = 0;
String GROUP_KEY_WORK_EMAIL = "com.android.example.WORK_EMAIL";
String CHANNEL_ID = "MY_CHANNEL_ID";
Notification newMessageNotification1 =
new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_map_position_icon)
.setContentTitle("First summary")
.setContentText("You will not believe...")
.setGroup(GROUP_KEY_WORK_EMAIL)
.build();
Notification newMessageNotification2 =
new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_map_nav_position_icon_grey)
.setContentTitle("Second summary")
.setContentText("Please join us to celebrate the...")
.setGroup(GROUP_KEY_WORK_EMAIL)
.build();
Notification summaryNotification =
new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setContentTitle("Total summary")
.setContentText("Two new messages")
.setSmallIcon(R.drawable.ic_wdw_dont_drive)
.setGroup(GROUP_KEY_WORK_EMAIL)
.setGroupSummary(true)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, newMessageNotification1);
notificationManager.notify(2, newMessageNotification2);
notificationManager.notify(SUMMARY_ID, summaryNotification);
}
The method createNotificationChannel()just creates the channel, I left it out here for better readability.
Now the documentation says:
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.
So the last notify() call shall be optional and creating the summaryNotification, too. But this example only works for me when I notify the summary notification. When I don't do that, the notifications are not grouped.
What is going wrong here?
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.
"Summary [text]" but not "Group summary notification". This just means that whatever text you set in summary notification style it will be replaced by combined text from grouped notifications for Android >= N.
This doesn't affect the fact that the notifications are not grouped without summary.
Yes, this was highly misleading for me too, had to learn it the hard way. Try building the group on Kitkat and compare it to Nougat one.

How to set badge count in Oreo without showing a notification?

I used to show a number in app icon using this library as follows:
ShortcutBadger.applyCount(context, numberToShow);
OneSignal also has same function in its Android SDK.
Now in Oreo, with the introduction of notification channels, things get complex to me. I can create a channel. Then, I can also create a notification as follows:
public static void createNotification(Context context, int numberToShow) {
Notification notification = new NotificationCompat.Builder(context, context.getString(R.string.notification_channel_id))
.setContentTitle("Dummy Title")
.setContentText("Dummy content")
.setSmallIcon(R.drawable.app_icon)
.setNumber(numberToShow)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(0, notification);
}
However, I have to show a notification with this solution, which I don't need and thus don't want. Is there any way in Oreo that I can achieve the same thing I have done previously, i.e. just showing 'notification dot' or a number attached to the app icon?
Sorry, but there is no SDK-level support for showing numbers or other badges on launcher icons, other than the Notification scenario that you described.
set the importance of the notification channel to
IMPORTANCE_MIN
like int importance = NotificationManager.IMPORTANCE_MIN;
and then create the channel as -
NotificationChannel nChannel = new NotificationChannel
(channelId, title, importance);
This will the set the badge count(shown on the long press of the icon) without notifying the user about any notification in the system tray. Though the notification will be in the tray, but will not pop up and quietly reside there.

Android notification is not showing

I need a program that will add a notification on Android. And when someone clicks on the notification, it should lead them to my second activity.
I have established code. The notification should be working, but for some reason it is not working. The Notification isn't showing at all. I don't know what am I missing.
Code of those files:
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setContentIntent(pIntent).setAutoCancel(true)
.setStyle(new Notification.BigTextStyle().bigText(longText))
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after it's selected
notificationManager.notify(0, n);
The code won't work without an icon. So, add the setSmallIcon call to the builder chain like this for it to work:
.setSmallIcon(R.drawable.icon)
Android Oreo (8.0) and above
Android 8 introduced a new requirement of setting the channelId property by using a NotificationChannel.
NotificationManager mNotificationManager;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// === Removed some obsoletes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId(channelId);
}
mNotificationManager.notify(0, mBuilder.build());
Actually the answer by Ć’ernando Valle doesn't seem to be correct. Then again, your question is overly vague because you fail to mention what is wrong or isn't working.
Looking at your code I am assuming the Notification simply isn't showing.
Your notification is not showing, because you didn't provide an icon. Even though the SDK documentation doesn't mention it being required, it is in fact very much so and your Notification will not show without one.
addAction is only available since 4.1. Prior to that you would use the PendingIntent to launch an Activity. You seem to specify a PendingIntent, so your problem lies elsewhere. Logically, one must conclude it's the missing icon.
You were missing the small icon.
I did the same mistake and the above step resolved it.
As per the official documentation:
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.
See http://developer.android.com/guide/topics/ui/notifiers/notifications.html
This tripped me up today, but I realized it was because on Android 9.0 (Pie), Do Not Disturb by default also hides all notifications, rather than just silencing them like in Android 8.1 (Oreo) and before. This doesn't apply to notifications.
I like having DND on for my development device, so going into the DND settings and changing the setting to simply silence the notifications (but not hide them) fixed it for me.
Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviours after this
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
You also need to change the build.gradle file, and add the used Android SDK version into it:
implementation 'com.android.support:appcompat-v7:28.0.0'
This worked like a charm in my case.
I think that you forget the
addAction(int icon, CharSequence title, PendingIntent intent)
Look here: Add Action
I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).
After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.
Notifications Overview, Notification anatomy
Create and Manage Notification Channels
For me it was an issue with deviceToken. Please check if the receiver and sender device token is properly updated in your database or wherever you are accessing it to send notifications.
For instance, use the following to update the device token on app launch. Therefore it will be always updated properly.
// Device token for push notifications
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
deviceToken = instanceIdResult.getToken();
// Insert device token into Firebase database
fbDbRefRoot.child("user_detail_profile").child(currentUserId).child("device_token")).setValue(deviceToken)
.addOnSuccessListener(
new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
});
I encountered a similar problem to yours and while searching for a solution I found these answers but they weren't as direct as I hoped they would be but it gives an Idea; Your notifications may not be showing because for versions >=8 notifications are done relatively differently there is a NotificationChannel which aids in managing notifications this helped me. Happy coding.
void Note(){
//Creating a notification channel
NotificationChannel channel=new NotificationChannel("channel1",
"hello",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
//Creating the notification object
NotificationCompat.Builder notification=new NotificationCompat.Builder(this,"channel1");
//notification.setAutoCancel(true);
notification.setContentTitle("Hi this is a notification");
notification.setContentText("Hello you");
notification.setSmallIcon(R.drawable.ic_launcher_foreground);
//make the notification manager to issue a notification on the notification's channel
manager.notify(121,notification.build());
}
Make sure your notificationId is unique. I couldn't figure out why my test pushes weren't showing up, but it's because the notification ids were generated based on the push content, and since I was pushing the same notification over and over again, the notification id remained the same.
Notifications may not be shown if you show the notifications rapidly one after the other or cancel an existing one, then right away show it again (e.g. to trigger a heads-up-notification to notify the user about a change in an ongoing notification). In these cases the system may decide to just block the notification when it feels they might become too overwhelming/spammy for the user.
Please note, that at least on stock Android (tested with 10) from the outside this behavior looks a bit random: it just sometimes happens and sometimes it doesn't. My guess is, there is a very short time threshold during which you are not allowed to send too many notifications. Calling NotificationManager.cancel() and then NotificationManager.notify() might then sometimes cause this behavior.
If you have the option, when updating a notification don't cancel it before, but just call NotificationManager.notify() with the updated notification. This doesn't seem to trigger the aforementioned blocking by the system.
If you are on version >= Android 8.1 (Oreo) while using a Notification channel, set its importance to high:
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
val pendingIntent = PendingIntent.getActivity(applicationContext, 0, Intent(), 0)
var notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setContentTitle("Title")
.setContentText("Text")
.setSmallIcon(R.drawable.icon)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.build()
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify(sameId, notification)

Categories

Resources