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

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

Related

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

Notification doesn't vibrate

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
}

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.

How can I set notification header when receiving push message?

I'm dev-ing notification when receiving a push message in android. So I wrote same way like this url. but I can not see the notification header box. how can I fix this code? I can see the small icon on status bar but cannot see the head up box
manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
FirebaseService
class FirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
Log.d("TAG", "Refreshed token: $token")
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d("TAG", "From: " + remoteMessage.from!!)
val messageBody = remoteMessage.notification?.body
val messageTitle = remoteMessage.notification?.title
val intent = Intent(this, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
val channelId ="1000"
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val inboxStyle = NotificationCompat.InboxStyle()
val notificationBuilder = NotificationCompat.Builder(this,channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setOngoing(true)
.setSound(defaultSoundUri)
//.setContentIntent(pendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.haii))
.setColor(getResources().getColor(R.color.colorPrimary))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setStyle(inboxStyle)
.setFullScreenIntent(pendingIntent,true)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val channelName ="Channel Name"
val channel = NotificationChannel(channelId,channelName,NotificationManager.IMPORTANCE_HIGH)
channel.enableLights(true)
channel.lightColor= 0x00FFFF
channel.setShowBadge(false)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0,notificationBuilder.build())
}
}

Android FCM Notification Cannot Be Clicked Second Time

I Have problem with my notification.
First way - I open my app, then I push notification from FCM first time, I click the notif, my code executed, I push again for second time, I click my notif, my code still execute, I try more more time is worked well.
Second way - My app still close, I push notif from FCM first time, then I Click the notif, so my app will open and my code executed, then I push notif again for second time, my code NOT executed, I try more more time still NOT working.
until I swipe my app, and try again, the problem still happen.
this is my code
class MyFirebaseMessagingService : FirebaseMessagingService() {
var userInformation = AccountTableDao()
val sp: SharedPreferences by lazy { SharedPreference.instance }
val gad: GetAccountData by lazy { AccountDatabase.instance }
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d("firebase", "INSTANCE ID ===> $token")
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
remoteMessage?.let {
sendNotification(it.data)
}
}
private fun sendNotification(messageData: Map<String, String>) {
var status = messageData.get("status")
val uuid = messageData.get("uuid")
val restaurantId = messageData.get("restaurantId")
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val titleText = messageData.get("title").toString()
val contentText = messageData.get("body").toString()
val intent = Intent(applicationContext, RestaurantMenuActivity::class.java)
intent.putExtra(Argument.NOTIF_UUID, uuid)
intent.putExtra(Argument.NOTIF_RESTAURANT_ID, restaurantId)
intent.putExtra(Argument.NOTIF_STATUS, status)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val pendingIntent = PendingIntent.getActivity(applicationContext,System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val notificationChannel = NotificationChannel("appety", "appety_notification", NotificationManager.IMPORTANCE_HIGH)
notificationManager .createNotificationChannel(notificationChannel)
notificationManager.notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, "1")
.setChannelId(System.currentTimeMillis().toString())
.setContentTitle(titleText)
.setStyle(NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_check_black_24dp)
.setLargeIcon( BitmapFactory.decodeResource(applicationContext.resources, R.drawable.logo_appety))
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorBonAppety))
.build())
}
else{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationManager .notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, System.currentTimeMillis().toString())
.setContentTitle(titleText)
.setStyle (NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_check_black_24dp)
.setLargeIcon( BitmapFactory.decodeResource(applicationContext.resources, R.drawable.logo_appety))
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorBonAppety))
.build())
} else {
notificationManager .notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, "1")
.setContentTitle(titleText)
.setStyle (NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.build())
}
}
}
companion object {
private val TAG = "token"
}
}
and manifest
<service
android:name=".service.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Why Pending Intent not working and how to fix that.
Sorry for my english and regard.
You should try setAutoCancel() method when creating the notification.
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder summary = new NotificationCompat.Builder(this);
summary.setAutoCancel(true);
And if you passing an intent to the notification, then use this
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);

Categories

Resources