Custom notification is not creating when I add custom layout - android

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)
}
}

Related

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

Not getting heads up notifications for a while when you swipe up local notifications

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())
}
}

Android custom notification sound not working on some device

I have set custom sound for notification. It's working for some device but not working on some device mostly Xiaomi device.
I have used this code:
private fun createNotificationChannel(){
val context = AppApplication.getContext()
val notificationManagerCompat = NotificationManagerCompat.from(context)
preChannelIds.forEach {
deleteChannel(notificationManagerCompat,it)
}
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val attributes = getAudioAttributes()
val soundUri = getSoundUri(context)
val importance = NotificationManagerCompat.IMPORTANCE_HIGH
val channelBuilder = NotificationChannelCompat.Builder(channelId, importance).apply {
setName(channelName)
setDescription(channelDescription)
setSound(soundUri, attributes)
setVibrationPattern(vibrationPattern)
setLightsEnabled(true)
setShowBadge(true)
}
val channel = channelBuilder.build()
notificationManagerCompat.createNotificationChannel(channel)
}
}
fun sendNotification(title:String, message:String){
val context = AppApplication.getContext()
val intent = ....
val notificationManagerCompat = NotificationManagerCompat.from(AppApplication.getContext())
val pendingIntent = PendingIntent.getActivity(
AppApplication.getContext(), notificationRequestCode, intent,
PendingIntent.FLAG_UPDATE_CURRENT)
val notificationBuilder = NotificationCompat.Builder(AppApplication.getContext(), channelId)
.setSmallIcon(getNotificationIcon())
.setContentTitle(title)
.setContentText(message)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setAutoCancel(true)
.setVibrate(vibrationPattern)
.setColor(ContextCompat.getColor(AppApplication.getContext(), R.color.colorPrimary))
.setContentIntent(pendingIntent)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
notificationBuilder.priority = NotificationCompat.PRIORITY_MAX
notificationBuilder.setSound(getSoundUri(context))
}
val notification = notificationBuilder.build()
notification.flags = Notification.FLAG_INSISTENT
notificationManagerCompat.notify(notificationRequestCode, notification)
}
Please help me to solve this issue for some device. Is there any other solution for this issue.

Android worker with foreground service does not show notifications

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.

Firebase Cloud Messaging received BUT doesn't Popup!!! - KOTLIN

This is my code!
I'm building an application that receives notifications from firebase.
The App receiving the notification but doesn't popup it.
Any Help!
class MyFirebaseMessagingService : FirebaseMessagingService() {
val TAG = "FirebaseMessagingService"
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
Log.d(TAG, "{$p0}")
if (p0.notification !=null){
showNotification(p0.notification?.title, p0.notification?.body)
}
}
private fun showNotification(title: String?, body: String?){
val intent=Intent(applicationContext, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent=PendingIntent.getActivities(
this,
0,
arrayOf(intent),
PendingIntent.FLAG_UPDATE_CURRENT
)
//val soundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo_border)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(2)
val notificationManager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d(TAG, "Refreshed token: $token")
}
I think it's because of the notification channel which came out with Android 8.0.
Call this function before building your notification.
private fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val existingChannel = notificationManager.getNotificationChannel(CHANNEL_ID)
if (existingChannel == null) {
// Create the NotificationChannel
val name = context.getString(R.string.defaultChannel)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
mChannel.description = context.getString(R.string.notificationDescription)
notificationManager.createNotificationChannel(mChannel)
}
}
}
And use this with your code
NotificationManagerCompat.from(context).apply {
cancelAll() // Remove prior notifications; only allow one at a time.
notify(1 or your notification id, notificationBuilder.build())
}
instead of
val notificationManager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification_icon)
.setTicker(title)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(pendingIntent)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setSound(defaultSoundUri)
.setContentText(message)
if (bitmap != null) {
notificationBuilder.setLargeIcon(bitmap)
}
val notificationManager = applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId,
channelName,
NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(notificationId, notificationBuilder.build())

Categories

Resources