I wanted to create a notification with heads up feature . Basically it is a alarm feature. And I wanted to show with notification using foreground. Now workmanager has the feature to run in foreground using setForeground . But it's not showing notifications as I implement it as following :
#HiltWorker
class NotificationWorker #AssistedInject constructor(
#Assisted context: Context,
#Assisted workerParams: WorkerParameters,
) : CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result {
Log.d(TAG, "doWork: notification worker called ")
setForeground(createForegroundInfo())
return Result.success()
}
private fun createForegroundInfo(): ForegroundInfo
{
val msg = "messgae "
val id = 34
val channelId = "show_reminder"
val channelName = "Reminder Notification"
val alarmSound: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
val vibratePattern = longArrayOf(500, 500, 500, 500, 500, 500, 500, 500, 500)
val customView = RemoteViews("packageName", R.layout.alarm_notification)
customView.setTextViewText(R.id.content, msg.trim())
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(channel)
}
...
val builder = NotificationCompat.Builder(applicationContext,channelId)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentText(msg.trim())
.setStyle(NotificationCompat.BigTextStyle()
.bigText(msg.trim()))
.setSmallIcon(R.drawable.ic_baseline_access_alarm_24)
.setSound(alarmSound)
.setVibrate(vibratePattern)
.setCustomHeadsUpContentView(customView)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
//notificationManager.notify(id, builder.build())
return ForegroundInfo(id,builder.build())
}
}
When calling notificationManager.notify(id, builder.build()) displays the notification but it won't stay long .How to make heads up notification stay long ?
Related
When I swipe up after the local notification comes, the application notifications don't appear on the screen for a while. What could be the reason for this? I've read something that when heads up notifications are swiped up, it sends a warning to the system to prevent heads up notifications for a certain period of time, but how can I prevent this? I don't have any problems getting notifications in my app other than that.
fun getChatChannels(): MutableList<NotificationChannel> {
val chatChannels = mutableListOf<NotificationChannel>()
val chatChannel = NotificationChannel(
IM_CHANNEL_ID,
Application.getString(R.string.chat_channel_name),
NotificationManager.IMPORTANCE_HIGH
)
chatChannel.setShowBadge(false)
chatChannel.group = MESSAGE_GROUP_ID
chatChannels.add(chatChannel)
return chatChannels }
private fun getChannelList(): MutableList<NotificationChannel> {
val channelList = mutableListOf<NotificationChannel>()
channelList.addAll(getChatChannels())
return channelList
}
fun createGroupsAndChannels() {
// 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 notificationManager =
Application.instance.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannelGroups(getGroupList())
notificationManager.createNotificationChannels(getChannelList())
}
Log.d(TAG, "Channels and groups created")
}
fun showChatNotification(destinationAddress: String, messageId: String, message: String) {
ThreadManager.createUITask {
val name = if (domainContact != null) {
"${domainContact.firstName} ${domainContact.lastName}"
} else {
destinationAddress
}
val notificationIntent = Intent(Application.instance, MainActivity::class.java)
notificationIntent.putExtra(
Application.getString(R.string.key_conversation_participant),
destinationAddress
)
notificationIntent.flags = Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
val pendingIntent = PendingIntent.getActivity(
Application.instance,
destinationAddress.hashCode(),
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val notificationId = UUID.randomUUID().hashCode()
val builder = NotificationCompat.Builder(Application.instance, IM_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification_message)
.setColor(ContextCompat.getColor(Application.instance, R.color.colorPrimary))
.setContentTitle(name)
.setContentText(message)
.setStyle(
NotificationCompat.BigTextStyle() // Expandable-Collapsible notification
.bigText(message)
)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.setVisibility(VISIBILITY_PUBLIC)
.setAutoCancel(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.addAction(getChatNotificationReplyAction(destinationAddress, notificationId, messageId))
}
chatNotifications.add(mapOf(destinationAddress to notificationId))
createNotifications(builder, notificationId)
Log.d(TAG, "Chat notification created")
}
private fun createNotifications(builder: NotificationCompat.Builder, notificationId: Int) {
with(NotificationManagerCompat.from(Application.instance)) {
notify(notificationId, builder.build())
}
}
I'm following this documentation to create a long-time worker running a foreground service, but no notification is shown.
The worker run, i see the logs.
The code:
override suspend fun doWork(): Result {
Log.d(TAG, "Worker start")
setForeground(createForegroundInfo("Hello from my notification"))
Log.d(TAG, "Worker end")
return Result.success()
}
private fun createForegroundInfo(progress: String): ForegroundInfo {
val channelId = applicationContext.getString(R.string.notification_channel_id)
val title = applicationContext.getString(R.string.notification_title)
// This PendingIntent can be used to cancel the worker
val intent = WorkManager.getInstance(applicationContext)
.createCancelPendingIntent(getId())
// Create a Notification channel if necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel()
}
val notification = NotificationCompat.Builder(applicationContext, channelId)
.setContentTitle(title)
.setTicker(title)
.setContentText(progress)
.setSmallIcon(R.drawable.ic_notifications_black_24dp)
.setOngoing(true)
.build()
return ForegroundInfo(1, notification)
}
#RequiresApi(Build.VERSION_CODES.O)
private fun createChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
val name = applicationContext.getString(R.string.notification_channel_name)
val descriptionText = applicationContext.getString(R.string.notification_channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channelId = applicationContext.getString(R.string.notification_channel_id)
val channel = NotificationChannel(channelId, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
The problem is that the doWork function lasted too short, not long enough to see the notification.
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)
}
I'm firing a notification after posting data to fcm , when i receive data back the notification is shown no problem but it has no sound no vibration even though i made sure that my sound and vibraton are enable in my phone , i'm not sure if i'm doing something wrong , please help me figure it out , thank you .
This is my application class code where i set the notification channel for oreo +
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
setUpNotification()
}
private fun setUpNotification(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val notificationChannel = NotificationChannel(
getString(R.string.channelid),getString(R.string.channelstring),
NotificationManager.IMPORTANCE_DEFAULT)
val ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
notificationChannel.description = "Notifications"
notificationChannel.enableLights(true)
notificationChannel.enableVibration(true)
notificationChannel.lightColor = Color.BLUE
notificationChannel.setSound(ringtone,audioAttributes)
val notificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as
NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
}
}
This is my notification code
private fun FireNotification(title : String, body : String, isVibrationEnabled : Boolean,
notificationchannelid : String){
val intent = Intent(applicationContext,MainActivity::class.java)
val taskBuilder = TaskStackBuilder.create(applicationContext).run {
addNextIntentWithParentStack(intent)
getPendingIntent(1,PendingIntent.FLAG_UPDATE_CURRENT)
}
val vibratePattern = longArrayOf(1000L, 1000L, 1000L, 1000L)
val notification = NotificationCompat.Builder(applicationContext, notificationchannelid)
notification.apply {
setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
setContentTitle(title)
setContentText(body)
setContentIntent(taskBuilder)
setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
addAction(R.drawable.default_icon,"Snooze",taskBuilder)
addAction(R.drawable.default_icon,"Action",taskBuilder)
priority = NotificationCompat.PRIORITY_HIGH
if(isVibrationEnabled){
notification.setVibrate(vibratePattern)
}
}
NotificationManagerCompat.from(applicationContext).notify(counter++,notification.build())
}
The solution to my issue was to simply set default sound as following
setDefaults(NotificationCompat.DEFAULT_SOUND)
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