Notification not showing when app is in foreground in Kotlin - android

I am using Firebase push notification in kotlin and below are the code snippet for showing push notification
mNotifyManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
createChannel(mNotifyManager)
val mBuilder = NotificationCompat.Builder(this, "bks-channel")
.setLargeIcon(largeIcon)
.setContentTitle("Bks")
.setSmallIcon(R.drawable.app_icon)
.setContentText(message)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
mNotifyManager.notify(getRandomNumber(), mBuilder.build())
And the createChannel() function is :
#TargetApi(26)
private fun createChannel(notificationManager: NotificationManager)
{
val name = "bks"
val description = "bks"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(name, name, importance)
mChannel.description = description
mChannel.enableLights(true)
mChannel.lightColor = Color.BLUE
notificationManager.createNotificationChannel(mChannel)
}
Below are the server logs:
array(1) {
[9]=>
array(2) {
["name"]=>
string(14) "ABL Staff USER"
["fcm_response"]=>
array(2) {
["fields"]=>
array(3) {
["data"]=>
array(4) {
["click_action"]=>
int(2)
["title"]=>
string(19) "Attendance Reminder"
["body"]=>
string(49) "Hi ABL Staff USER, Please mark your attendance ! "
["sound"]=>
string(7) "default"
}
["registration_ids"]=>
array(11) {
[0]=>
string(152) "device_token_1"
}
["notification"]=>
array(4) {
["click_action"]=>
int(2)
["title"]=>
string(19) "Attendance Reminder"
["body"]=>
string(49) "Hi ABL Staff USER, Please mark your attendance ! "
["sound"]=>
string(7) "default"
}
}
Same are working for below android o in foreground and background but not in android o or above

FCM has sent two type of notification
Notification Message
Data Message
Send the data message to show a notification when the app in the background
For more details check the below link
Firebase data message

Are you creating channel by name "bks-channel" ? Looks like you are not creating bks-channel instead you are creating channel by name bks.
Update your create channel method.
#TargetApi(26)
private fun createChannel(notificationManager: NotificationManager) {
val name = "bks-channel"
val description = "bks"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(name, name, importance)
mChannel.description = description
mChannel.enableLights(true)
mChannel.lightColor = Color.BLUE
notificationManager.createNotificationChannel(mChannel)
}

Related

How to combine all app notifications together?

I want to show the app name on top and all the notifications of the app clubbed below it. I am receiving the notification from firebase and using this code:
val messagingStyle = Notification.MessagingStyle(person)
val remoteInput = RemoteInput.Builder(KEY_TEXT_REPLY).also {
it.setLabel(context.getString(R.string.type_to_reply))
}.build()
val mChannel =
NotificationChannel(channelId, newMessage.text, NotificationManager.IMPORTANCE_HIGH)
mChannel.description = newMessage.text.toString()
mChannel.enableVibration(true)
val notifManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notifManager.createNotificationChannel(mChannel)
val statusBarNotification = notifManager.activeNotifications.firstOrNull {
it.id == channelId.toInt()
}
if (statusBarNotification == null) {
val builder: Notification.Builder = Notification.Builder(context, channelId)
val pendingIntent: PendingIntent =
PendingIntent.getActivity(
context,
channelId.toInt(),
navIntent,
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
)
builder.setContentTitle(newMessage.text)
.setSmallIcon(R.drawable.my_logo) // required
.setContentText(newMessage.text) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.addAction(
getNotificationIntent(context, channelId.toInt(), remoteInput)
)
.setWhen(newMessage.timestamp)
.setStyle(messagingStyle.addMessage(newMessage))
.setContentIntent(pendingIntent)
.setGroup(MY_NOTIFICATIONS)
.setGroupSummary(true)
val notification = builder.build()
notifManager.notify(channelId.toInt(), notification)
} else {
var notificationBuilder = recoverBuilder(context, statusBarNotification.notification)
notificationBuilder.also {
val messageStyle = it.style as Notification.MessagingStyle
messageStyle.addMessage(newMessage.text, newMessage.timestamp, person)
it.style = messageStyle
}
notifManager.notify(channelId.toInt(), notificationBuilder.build())
}
This is what I want(like whatsapp)
[![whatsapp screenshot]]
[1]: https://i.stack.imgur.com/1j3Xf.jpg
But this is how it is appearing right now. all the notifications are seperate.
[![screenshot]]
[2]: https://i.stack.imgur.com/UdhrY.jpg
There are similar posts here about merging notifications. They offer different approaches so check them out to see which one is applicable to your use case:
Firebase merge similar notifications in Android
How to merge push notifications like whatsapp does in FirebaseMessagingService
Can't get grouped/bundled notifications with
FirebaseMessagingService

How to make Android Notifications even when the app is closed like any chat app

I want to make Android Notifications to show even when the app is closed like any chat app
i tried using this->
fun createnotfictionchannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Title"
val desc = "desc"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("id", name, importance).apply {
description = desc
}
val notificationManager : NotificationManager? = requireActivity().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
notificationManager!!.createNotificationChannel(channel)
}
}
fun sendNote(title:String, description:String){
val pendingIntent: PendingIntent =
Intent(requireContext(), MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(requireContext(), 0, notificationIntent,
PendingIntent.FLAG_IMMUTABLE)
}
val builder =
NotificationCompat.Builder(requireContext())
.setSmallIcon(R.drawable.ic_baseline_notifications_24)
.setContentTitle(title)
.setContentText(description)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setCategory(Notification.CATEGORY_MESSAGE)
.setAutoCancel(true)
with(NotificationManagerCompat.from(requireContext())){
notify(1, builder.build())
}
}
But once the app is closed there isn't any notifications,
What can i use that has as little code possible?
Thanks

Custom notification is not creating when I add custom layout

I have to create a custom notification like what's app calling notification. Notification does not create if I add my custom layout to the NotificationCompat Builder. Below is my code to create notification.
Creating Notification
context?.let {
val notificationLayout = RemoteViews(it.packageName, R.layout.custom_notification_collapsed)
val notificationLayoutExpanded = RemoteViews(it.packageName, R.layout.custom_notification)
notificationLayout.setImageViewResource(R.id.iv_icon, R.drawable.icon)
notificationLayout.setTextViewText(R.id.tv_app_name, it.getString(R.string.app_name))
notificationLayout.setTextViewText(R.id.time_stamp, it.getString(R.string.just_now))
notificationLayoutExpanded.setImageViewResource(R.id.iv_icon,R.drawable.icon)
notificationLayoutExpanded.setTextViewText(R.id.tv_app_name, it.getString(R.string.app_name))
notificationLayoutExpanded.setTextViewText(R.id.content, it.getString(R.string.text))
notificationLayout.setTextViewText(R.id.time_stamp, it.getString(R.string.just_now))
var builder = NotificationCompat.Builder(it, AppConstants.CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setTicker("Noification is created")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
var customNotificationCompat: NotificationManagerCompat = NotificationManagerCompat.from(it)
customNotificationCompat.notify(0, builder.build())
}
Creating Channel and calling it from Application class:
fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = context.getString(R.string.app_name)
val descriptionText = context.getString(R.string.text)
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(AppConstants.CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}

Notification .setContentText not displayed on Android 10

I have a simple expandable notification.
Normal Layout:
Title
Short Text (.setContentText)
Explanded:
Title
Long Text (.setStyle)
In Android 10 (API 29) this does not work anymore as only the long text is partially shown. Take a look at the litte arrows in the top right corner.
val builder = NotificationCompat.Builder(this, CHANNEL_TEST_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("This is the title")
.setContentText("This is the content, which is not displayed in Android 10.")
.setStyle(NotificationCompat.BigTextStyle().bigText("The only displayed text in Android 10. contentText missing."))
.setPriority(NotificationCompat.PRIORITY_HIGH) // by channel from Android 8
.setAutoCancel(true) // Android 8
with(NotificationManagerCompat.from(this)) {
// notificationId is a unique int for each notification that you must define
notify(101, builder.build())
}
private const val CHANNEL_TEST_ID = "TEST"
private fun 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) {
val name = "Test"
val descriptionText = "Test"
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(CHANNEL_TEST_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
Is this a bug or a feature?
Google has confirmed this is a bug: https://issuetracker.google.com/issues/141403558

NotificationManagerCompat on Android Oreo

Is there a way to set channels on Android Oreo when using NotificationManagerCompat and NotificationCompat?
Since NotificationManagerCompat is just a wrapper class that makes life easier, you can create the channels normally:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.channel_title)
val description = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_HIGH
val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
mChannel.description = description
mChannel.enableLights(true)
mChannel.lightColor = Color.parseColor("#5B3C88")
mChannel.enableVibration(true)
mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
val manager = (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
manager.createNotificationChannel(mChannel)
}
And then use the NotificationManagerCompat when you post the notifications, but don't forget to construct the notification using the new constructor:
NotificationCompat.Builder(context, CHANNEL_ID)
Using NotificationManagerCompat with AndroidX is the recommended way.
NotificationManagerCompat now supports Notification channels. The new version Added Notification channels methods to NotificationManagerCompat so developers can use only NotificationManagerCompat when working with notifications.
For Java, include the following in your build.gradle file
implementation 'androidx.core:core:1.2.0'
For Kotlin, include the following instead of the above dependency in your build.gradle file
implementation 'androidx.core:core-ktx:1.2.0'
To display a notificaiton, you will have to do the following
Create and register notification channel.
Create a notification.
Show the notification
The snippets below are in Kotlin, but you can also use Java if you want.
1. Create and register a notification channel.
Notification channels provide a common visual and auditory experience for notifications of a similar type. Since their introduction in API 26, you are now required to set a channel for a notification, otherwise they will not display on newer versions of Android.
So define a helper method as shown below to create a notification channel for you.
//define your channel id
val CHANNEL_ID = "com.yourpackagename.your_channel_id"
//create notification channel for android Oreo and above devices.
if (Build.VERSION.SDK_INT >= 26) {
val channel = NotificationChannel(CHANNEL_ID , "Your channel name", NotificationManager.IMPORTANCE_DEFAULT)
NotificationManagerCompat.from(this).createNotificationChannel(channel)
}
2. Create a notification.
Use the NotificationCompat.Builder to create a Notificaiton. Please note that the CHANNEL_ID is passed to the builder.
var builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Much longer text that cannot fit one line...")
.setStyle(NotificationCompat.BigTextStyle()
.bigText("Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
3. Show the notification
To make the notification appear, call NotificationManagerCompat.notify(), passing it a unique ID for the notification and the result of NotificationCompat.Builder.build()
NotificationManagerCompat.from(this).notify(notificationId, builder.build())
That's all :)
I usually use this class to manage notification channels:
class NotificationManager(private val context: Context) {
companion object {
private val CHANNEL_ID = "YOUR_CHANNEL_ID"
private val CHANNEL_NAME = "Your human readable notification channel name"
private val CHANNEL_DESCRIPTION = "description"
}
#RequiresApi(Build.VERSION_CODES.O)
fun getMainNotificationId(): String {
return CHANNEL_ID
}
#RequiresApi(Build.VERSION_CODES.O)
fun createMainNotificationChannel() {
val id = CHANNEL_ID
val name = CHANNEL_NAME
val description = CHANNEL_DESCRIPTION
val importance = android.app.NotificationManager.IMPORTANCE_LOW
val mChannel = NotificationChannel(id, name, importance)
mChannel.description = description
mChannel.enableLights(true)
mChannel.lightColor = Color.RED
mChannel.enableVibration(true)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
mNotificationManager.createNotificationChannel(mChannel)
}
}
Then you can use util like this
fun createNotificationCompatBuilder(context: Context): NotificationCompat.Builder {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return NotificationCompat.Builder(context, NotificationManager(context).mainNotificationId)
} else {
return NotificationCompat.Builder(context)
}
}
This way you can use it in any place of your application with signature just like you have used before and you can easily change it in case of future changes.

Categories

Resources