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
}
Related
I have two forground service FS1 and FS2 , with each one i create notification , if FS1 is running and i start FS2 the old notification get replaced , i want both to stay ,
this is how i create notification
private fun createNotification(): Notification {
val notificationChannelId = "123"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
notificationChannelId,
"Notification service channel",
NotificationManager.IMPORTANCE_HIGH
).let {
it.description = "Notification Service channel"
it.enableLights(true)
it.lightColor = Color.RED
it.enableVibration(true)
it.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
it
}
notificationManager.createNotificationChannel(channel)
}
val pendingIntent: PendingIntent = Intent(this, MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(this, 0, notificationIntent, 0)
}
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(
this,
notificationChannelId
) else Notification.Builder(this)
return builder
.setContentTitle("title")
.setContentText("Content")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.notification_icon)
.setTicker("Ticker text")
.setPriority(Notification.PRIORITY_HIGH)
.build()
}
and in the onCreate methode
val notification = createNotification()
startForeground(1, notification)
and in the other service i create notification with the same way !
Ok my bad , i found out why , at onCreate methode , in both services i was using id 1 , i should use different id
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())
I'm creating a channel with custom sound. The notifications are correctly displayed but the sound played is still the default one.
Creation of the channel
val audioAttribute = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
val sound = Uri.Builder().scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(packageName)
.path(R.raw.notifsound.toString()).build()
alertChannel.apply {
enableVibration(true)
description = "Signal alert channel"
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
setSound(sound, audioAttribute)
}
notificationManager.createNotificationChannels(listOf(locationNotificationChannel,gpsStatusChannel,alertChannel))
I checked the URI with this
(contentResolver as ContentResolver).openInputStream(sound)
And it can read the file.
I found the problem.
Once you create a notification channel, you can't change the sound of it.
So you have two solutions:
Uninstall the app and install again
Or change the notification channel id to create a new one with the right configuration.
Hope this help.
I solved the issue by uninstalling the app and reinstalling it
private fun sendNotification(remoteMessage: RemoteMessage) {
val fullScreenIntent = Intent(this, IncomingActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
putExtra(Constants.ROOM_ID, remoteMessage.data[Constants.ROOM_ID])
putExtra(Constants.REMOTE_MSG_INVITER_TOKEN, remoteMessage.data[Constants.REMOTE_MSG_INVITER_TOKEN])
}
val fullScreenPendingIntent: PendingIntent? = TaskStackBuilder.create(this).run {
// Add the intent, which inflates the back stack
addNextIntentWithParentStack(fullScreenIntent)
// Get the PendingIntent containing the entire back stack
getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
}
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build()
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(resources.getString(R.string.app_name), "Incoming call...", NotificationManager.IMPORTANCE_HIGH)
notificationChannel.description = "Someone is calling you..."
notificationChannel.setSound(Settings.System.DEFAULT_RINGTONE_URI, audioAttributes)
notificationManager.createNotificationChannel(notificationChannel)
}
val notificationBuilder =
NotificationCompat.Builder(this, resources.getString(R.string.app_name))
.setSmallIcon(R.drawable.icon)
.setContentTitle("Incoming call")
.setContentText("Someone is calling you...")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setAutoCancel(true)
.setSound(Settings.System.DEFAULT_RINGTONE_URI)
.setChannelId(resources.getString(R.string.app_name))
.setContentIntent(fullScreenPendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.icon))
val incomingCallNotification = notificationBuilder.build()
notificationManager.notify(0, incomingCallNotification)
}
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)
}
I need to develop custom turn off/on push notification. Value "on" or "off" I get from SharedPreferences.
In Foreground the option of turn off works well because it can set in onMessageReceived.
But how to do this options for Kill and Background modes?
For sending push notifications I use Postman.
My code in FMC:
class MyFirebaseMessagingService : FirebaseMessagingService() {
private val CURRENT_PUSH = "currentPush"
private var sPref: SharedPreferences? = null
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
if(loadCurrentPushNotification()) {
if (remoteMessage!!.data != null) sendNotification(remoteMessage)
}
}
private fun sendNotification(remoteMessage: RemoteMessage) {
val data = remoteMessage.data
val title = data["title"]
val content = data["content"]
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val NOTIFICATION_CHANNEL_ID = "1234"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant") val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID,
"SA Notification",
NotificationManager.IMPORTANCE_MAX)
notificationChannel.description = "SA channel notification"
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.vibrationPattern = longArrayOf(0, 1000, 500, 1000)
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
}
val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.sa_launcher)
.setContentTitle(title)
.setContentText(content)
.setContentInfo("Breaking")
notificationManager.notify(1, notificationBuilder.build())
}
private fun loadCurrentPushNotification(): Boolean { //to read the status push notification from SharedPreferences
sPref = getSharedPreferences("pushesOnOff", Context.MODE_PRIVATE)
return sPref!!.getBoolean(CURRENT_PUSH, true)
}
}
I suspect that your push notification payload/content contains the notification key like
notification : {
'title':'This is title'
}
If this is true, then you will not receive the onMessageReceived callback when your app is killed and hence your check will not work. In order to prevent this, remove the notification from your payload and only send data and it should work without any change on android side.
You can read about this behavior HERE.