I am working on an Android APP which has two foreground services and wants to group the notification into one Group. It is possible to do this? I have used NotificationCompat.Builder setGroup(String groupKey) to enable Group Notification, but it does not work.
NotificationHelper.kt
enum ChannelType{ ID1, ID2}
fun getNotificationChannelID(context: Context, channelType: ChannelType) : String? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelID = channelType.channelID
val description = channelType.reourceID
val channel = NotificationChannel(channelID, description,
NotificationManager.IMPORTANCE_HIGH);
val mNotificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE)
as android.app.NotificationManager
mNotificationManager.createNotificationChannel(channel)
return channelID
}
return null;
}
fun createBuilder(context: Context, channelId: String, title: String, content: String,
ongoing: Boolean, autoCancel: Boolean,
style: NotificationCompat.Style, #DrawableRes icon: Int,
priority: Int, vibratePattern: LongArray): NotificationCompat.Builder {
val builder = NotificationCompat.Builder(context, channelId)
builder.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(autoCancel)
.setOngoing(ongoing)
.setGroup(GROUP_KEY_NOTIF)
.setStyle(style)
.setGroupSummary(true)
return builder
}
}
from Service 1
onStartCommand() {
var channelID = getNotificationChannelID(context, ChannelType.ID1)
startForeground(NOTIFICATION_ID1,createBuilder(context,
channelID,
"title",
"description",
ongoing = false,
autocancel = true,
someIcon,
BigTextStyle,
priority, vibratePattern )
.build());
}
from service 2
onStartCommand() {
var channelID = getNotificationChannelID(context, ChannelType.ID1)
startForeground(NOTIFICATION_ID1,createBuilder(context,
channelID,
"title",
"description",
ongoing = false,
autocancel = true,
someIcon,
BigTextStyle,
priority, vibratePattern)
.build());
}
Am I missing anything? I have also set ongoing to false, still no change in result.
Thanks in advance.
Related
const val channelId = "notification_channel"
const val channelName = "com.deskmateai.t2chaiwala"
val vibration = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200)
class MyFirebaseMessagingService: FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
generateNotification(remoteMessage.notification!!.title!!, remoteMessage.notification!!.body!!)
}
// generating notification
private fun generateNotification(title: String, description: String){
val builder: NotificationCompat.Builder = NotificationCompat.Builder(applicationContext, channelId)
.setContentTitle(title)
.setSmallIcon(R.drawable.tea_notify_logo)
.setAutoCancel(true)
.setContentText(description)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setDefaults(NotificationCompat.DEFAULT_VIBRATE)
.setVibrate(longArrayOf(500, 500))
val v = applicationContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
v.vibrate(1000)
val manager: NotificationManagerCompat = NotificationManagerCompat.from(applicationContext)
manager.notify(1, builder.build())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
channel.enableLights(true)
channel.enableVibration(true)
channel.vibrationPattern = vibration
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
manager.notify(1, builder.build())
}
}
I am making an app in android for that i have integrated firebaase push notification, but my hone is not vibrating when notification come .
I have also added vibration permission in android manifest file. and as you can see in code i have done everything to vibrate my phone on notification but it is not.
You need to set the vibration when you are creating the channel. Also, make sure to reinstall your app to apply channel changes.
private fun createCallNotificationChannel(): NotificationChannelCompat {
val channel = NotificationChannelCompat.Builder(
INCOMING_CALL_CHANNEL_ID,
NotificationManagerCompat.IMPORTANCE_HIGH
).setName("Incoming notification")
.setDescription("Incoming notification alerts")
.setVibrationEnabled(true)
.build()
return channel
}
I am trying to integrate Firebase Cloud Messages into my app. The code I used in the showNotification function is from the Android User Interface Samples. I tried it in the Activity and it worked but am not sure why it's not working in the service. The println is showing the function is getting called and values are coming as expected. Is there anything am missing from the function?
class MessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.data.isNotEmpty()) {
val message = Gson().fromJson(remoteMessage.data.toString(), Message.Res::class.java).payload!!
showNotification(message.title, message.body, message.count)
}
}
private fun showNotification(title: String?, body: String?, count: Int = 0) {
println("_print::showNotification(title:$title, body:$body, count:$count)")
val mainPendingIntent = PendingIntent.getActivity(
applicationContext, BuildConfig.REQUEST_CODE,
Intent(applicationContext, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(applicationContext, "channel_email_1")
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round))
.setContentIntent(mainPendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.primary))
.setSubText(if (count > 1) "You have $count pending notifications" else title)
.setCategory(Notification.CATEGORY_EMAIL)
.setPriority(1)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
NotificationManagerCompat.from(applicationContext)
.notify(BuildConfig.NOTIFICATION_ID, builder.build())
}
}
Instead of
val mainPendingIntent = PendingIntent.getActivity(
applicationContext, BuildConfig.REQUEST_CODE,
Intent(applicationContext, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
NotificationManagerCompat.from(applicationContext)
.notify(BuildConfig.NOTIFICATION_ID, builder.build())
I use:
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
setupChannels(notificationManager, builder)
// Create pending intent, mention the Activity which needs to be triggered
// when user clicks on notification.
val notificationId = Random.nextInt()
navigateToScreen(builder, notificationId)
val notification = builder.build()
notificationManager.notify(notificationId, notification)
}
private fun setupChannels(notificationManager: NotificationManager,
builder: NotificationCompat.Builder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "channel_email_1"
val channel = NotificationChannel(channelId, "title",
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "body"
// Add other settings.
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
canShowBadge()
setShowBadge(true)
}
notificationManager.createNotificationChannel(channel)
builder.setChannelId(channelId)
}
}
private fun navigateToScreen(builder: NotificationCompat.Builder,
notificationId: Int) {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, notificationId, intent,
PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(pendingIntent)
}
An application receives push notifications. They can be different (payment, order, chat), so I have to show them all, not replacing old with new. A problem is that in old emulators (API 19) all push notifications are shown separately.
In newer emulators they are groupped into one, but (if I'm not mistaken) after 3 received notifications.
Data sent from FCM:
{
"to": "<push token>",
"data": {
"title": "Application name",
"message": "See a message",
"screen": "Main screen",
...
}
}
MyFirebaseMessagingService:
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val textStyle = NotificationCompat.BigTextStyle()
val title: String
val body: String
if (remoteMessage.data.isNullOrEmpty()) {
title = remoteMessage.notification?.title ?: ""
body = remoteMessage.notification?.body ?: ""
} else {
title = remoteMessage.data["title"] ?: ""
body = remoteMessage.data["message"] ?: ""
}
val notificationBuilder = NotificationCompat.Builder(this,
getString(R.string.default_notification_channel_id))
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setStyle(textStyle)
.setSound(soundUri)
.setSmallIcon(R.drawable.ic_notification_icon)
.setAutoCancel(true) // Dismiss the notification on click.
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
setupChannels(notificationManager, notificationBuilder)
// Create pending intent, mention the Activity which needs to be triggered
// when user clicks on notification.
val notificationId = Random.nextInt()
navigateToScreen(notificationBuilder, notificationId, remoteMessage)
val notification = notificationBuilder.build()
notificationManager.notify(notificationId, notification)
}
private fun setupChannels(notificationManager: NotificationManager,
notificationBuilder: NotificationCompat.Builder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = getString(R.string.default_notification_channel_id)
val channel = NotificationChannel(channelId, "title",
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "body"
enableLights(true)
enableVibration(true)
lightColor = Color.CYAN
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
canShowBadge()
setShowBadge(true)
}
notificationManager.createNotificationChannel(channel)
notificationBuilder.setChannelId(channelId)
}
}
private fun navigateToScreen(notificationBuilder: NotificationCompat.Builder,
notificationId: Int,
remoteMessage: RemoteMessage) {
val intent = getNavigationIntent(remoteMessage)
val pendingIntent = PendingIntent.getActivity(this, notificationId, intent,
PendingIntent.FLAG_UPDATE_CURRENT)
notificationBuilder.setContentIntent(pendingIntent)
}
private fun getNavigationIntent(remoteMessage: RemoteMessage): Intent {
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("screen", remoteMessage.data["screen"])
return intent
}
I have tried many solutions but none of them are worked. I am able receive FCM notification when app is active, but not getting notification when app is background or killed.
you need to create a service class extending FirebaseMessagingService and override onMessageReceived method in that class to send notification
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
try {
message.notification?.let {
showNotification(
it.title ?: "",
it.body ?: ""
)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
you are now getting the notification info from backend and showing it as a notification by using the function showNotification. of course, you must implement the function showNotification. it just a simple function for showing notifications in android
Edit: this the implementation of the function, add this to your class
class MyFirebaseMessagingService : FirebaseMessagingService() {
companion object {
const val channelId = "Channel"
const val channelName = "MyChannel"
const val smallIcon: Int = R.drawable.ic_logo
const val notificationId = 1
}
fun showNotification(myTitle: String, myBody: String) {
val notificationBuilder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(applicationContext, channelId)
} else {
Notification.Builder(applicationContext)
}
val intent = Intent(applicationContext, HomeActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
applicationContext,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val notificationManager =
applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
when {
Build.VERSION.SDK_INT >= 26 -> {
val channel = NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
notificationBuilder
.setContentIntent(pendingIntent)
.setContentText(myBody)
.setSmallIcon(smallIcon)
.setContentTitle(myTitle)
}
Build.VERSION.SDK_INT >= 24 -> notificationBuilder
.setContentText(myBody)
.setContentTitle(myTitle)
.setSmallIcon(smallIcon)
.setContentIntent(pendingIntent)
else -> notificationBuilder
.setContentText(myBody)
.setContentTitle(myTitle)
.setSmallIcon(smallIcon)
.setContentIntent(pendingIntent)
}
notificationManager.notify(notificationId, notificationBuilder.build())
}
}
If you want to get notification when app is background or killed your json object has to be this like:
{
"data":{
"title" : "your_title",
"body" : "your_body"
},
"to": "device_token",
"priority": "high"
}
You can catch notification onMessageReceived
Tried Searching With no Luck yet
i am testing on API 24
whats wrong with this code? the notification is showing correctly but is not a heads-up notification though i specified the priority to high and added vibration and sound correctly.
Please any help would be appreciated
Here is my code:
private fun sendNotification(title: String, message: String) {
val mNotificationCompatBuilder = mNotificationUtils.getNotificationBuilder(
title,
message,
false,
R.drawable.ic_logo,
NotificationUtils.ALERT_MESSAGES_ID
)
mNotificationCompatBuilder.setStyle(NotificationCompat.BigTextStyle().bigText(message))
mNotificationUtils.openTopActivityOnClick(mNotificationCompatBuilder, FTApplication.applicationContext())
mNotificationUtils.setSoundAndVibrate(mNotificationCompatBuilder)
val mNotificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify((title+message).hashCode(), mNotificationCompatBuilder.build())
}
fun getNotificationBuilder(title: String, body: String, onGoing: Boolean, icon: Int, id: String): NotificationCompat.Builder {
val largeIcon = BitmapFactory.decodeResource(
context.resources,
R.drawable.ic_logo
)
return NotificationCompat.Builder(context, id)
.setSmallIcon(icon)
.setLargeIcon(largeIcon)
.setBadgeIconType(icon)
.setContentTitle(title)
.setContentText(body)
.setOngoing(onGoing)
.setAutoCancel(!onGoing)
.setWhen(System.currentTimeMillis())
}
fun setSoundAndVibrate(builder: NotificationCompat.Builder) {
#Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) builder.priority = NotificationManager.IMPORTANCE_HIGH
else builder.priority = Notification.PRIORITY_HIGH
builder.priority = NotificationCompat.PRIORITY_HIGH // heads-up test
val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
builder.setSound(alarmSound)
builder.setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
builder.setDefaults(Notification.DEFAULT_ALL)
}
here is the channel im creating (which is not used since as mentioned i am testing now on API 24)
#RequiresApi(Build.VERSION_CODES.O)
private fun createAlertMessageChannel() {
if (getManager()!!.getNotificationChannel(ALERT_CHANNEL_NAME) != null) {
return
}
// create alert channel
val alertChannel = NotificationChannel(
ALERT_MESSAGES_ID,
ALERT_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH
)
alertChannel.description = "For Alerting User of Events"
alertChannel.setShowBadge(false)
alertChannel.enableLights(true)
alertChannel.enableVibration(true)
//alertChannel.setSound(null, null)
// Sets the notification light color for notifications posted to this channel
alertChannel.lightColor = Color.GREEN
// Sets whether notifications posted to this channel appear on the lock screen or not
alertChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
getManager()!!.createNotificationChannel(alertChannel)
}