if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val existingChannel = notificationManager.getNotificationChannel(id)
if (existingChannel != null) {
notificationManager.deleteNotificationChannel(id)
}
val channel = NotificationChannel(id, name, importance)
channel.description = description
channel.enableLights(true)
channel.setShowBadge(true)
channel.setBypassDnd(dnd)
channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
channel.lightColor = R.color.cornflower_blue_dark
channel.enableVibration(true)
channel.setSound(path,
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build()
)
notificationManager?.createNotificationChannel(channel)
}
I want to play custom sound notifications in Android. I have mentioned that in notification channel. But setSound is not working.
When the app is in background it wont call onMessageReceived().
And the channel.setSound() is also not working.
I want to have App Provided Sound for notifications.
Related
I am using Firebase FCM service for my android app. Facing the listed down issues in it.
Sometimes when app receives notifications it doesn't sound. Below is the code snippet.
private fun createNotificationChannel(
context: Context, id: String, name: String, description: String,
path: Uri?, dnd: Boolean, importance: Int,
notificationManager: NotificationManager
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val existingChannel =
notificationManager.getNotificationChannel(id)
if (existingChannel != null) {
notificationManager.deleteNotificationChannel(id)
}
val mAudioManager =
context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
mAudioManager.setStreamVolume(
AudioManager.STREAM_ALARM,
mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM),
0
)
val channel = NotificationChannel(id, name, importance)
channel.description = description
channel.enableLights(true)
channel.setShowBadge(true)
channel.describeContents()
channel.setBypassDnd(dnd)
channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
channel.lightColor = R.color.red
channel.enableVibration(true)
if (id == CHANNEL_ID_NORMAL_PRIORITY) {
if (!SharedPrefUtils.getSharedPrefIsAppInForeground(context)) {
channel.setSound(
path,
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
)
}
} else if (id == CHANNEL_ID_HIGH_PRIORITY) {
channel.setSound(
path,
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
)
}
notificationManager.createNotificationChannel(channel)
}
}
If App is not running for long time then the method onMessageReceived() of firebase messaging service is not getting called. In this case, when the app comes to the foreground, I am receiving notifications.
In push notification, I am sending only data payload because when the app is in background (either running or closed) and receives notification, if we use notification payload it won't set large icon to the banner. Below is code snippet for Push Notification.
AndroidConfig androidConfig = AndroidConfig.builder()
.setTtl(3600 * 1000)
.setPriority(AndroidConfig.Priority.HIGH)
//.setNotification(androidNotification)
.putData("title", title)
.putData("body", StringEscapeUtils.unescapeJava(content))
.putData("icon", icon)
.putData("sound", soundData)
.putData("channelid", channelId)
.build();
Message msg = Message.builder()
.setAndroidConfig(androidConfig)
.setToken(token)
.build();
String response = FirebaseMessaging.getInstance().send(msg);
Just like Micheal pointed out in the comment, this is (unfortunately) the expected behavior of the FCM when using the notification field.
Read more in the Handling messages section of the documentation. And the important bit:
The usual fix for such scenarios is to change the way FCMs are structured:
Do not use notification field (leave it completely unused), but use the data field and build your local push notifications based on that.
I am playing around with notifications on Wear OS and testing on a Fossil Falster 3 with Android API 28.
Why is the following notification not being triggered, in an standalone app.
The code is pretty much right from the Google documentation.
button_in.setOnClickListener {
val notificationId = 1
// The channel ID of the notification.
val id = "my_channel_01"
// Build intent for notification content
val viewPendingIntent = Intent(this, MainActivity::class.java).let { viewIntent ->
PendingIntent.getActivity(this, 0, viewIntent, 0)
}
// Notification channel ID is ignored for Android 7.1.1
// (API level 25) and lower.
val notificationBuilder = NotificationCompat.Builder(this, id)
.setLocalOnly(true)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("TITLE")
.setContentText("TEXT")
.setContentIntent(viewPendingIntent)
NotificationManagerCompat.from(this).apply {
notify(notificationId, notificationBuilder.build())
}
Log.d(TAG, "button was pressed!")
}
I can see the "button was pressed!" text, but I am not getting any notifications.
Watch apps require a notification channel, unlike Android apps which do not work like this.
In your code, val notificationId = 1 refers to the notification channel ID.
You can construct a NotificationChannel and register it like this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel
val name = getString(R.string.channel_name)
val descriptionText = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(1, name, importance) // 1 is the channel ID
mChannel.description = descriptionText
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
Notice in the commented code, in val mChannel = ..., you can see that the first parameter value 1 refers to the channel ID, as specified in your code in the OP.
You can read more about notification channels here: https://developer.android.com/training/notify-user/channels
I want to play custom sound notifications in Android.
I have mentioned that in notification channel, but setSound is not working.
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
val existingChannel=notificationManager.getNotificationChannel(id)
if(existingChannel!=null)
{notificationManager.deleteNotificationChannel(id)}
val channel = NotificationChannel(id, name, importance)
channel.description = description
channel.enableLights(true)
channel.setShowBadge(true)
channel.setBypassDnd(dnd)
channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
channel.lightColor = R.color.cornflower_blue_dark
channel.enableVibration(true)
channel.setSound(path,
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build())
notificationManager?.createNotificationChannel(channel)
}
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)
}
I am using Firebase push notification in kotlin and below are the code snippet for showing push notification
mNotifyManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
createChannel(mNotifyManager)
val mBuilder = NotificationCompat.Builder(this, "bks-channel")
.setLargeIcon(largeIcon)
.setContentTitle("Bks")
.setSmallIcon(R.drawable.app_icon)
.setContentText(message)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
mNotifyManager.notify(getRandomNumber(), mBuilder.build())
And the createChannel() function is :
#TargetApi(26)
private fun createChannel(notificationManager: NotificationManager)
{
val name = "bks"
val description = "bks"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(name, name, importance)
mChannel.description = description
mChannel.enableLights(true)
mChannel.lightColor = Color.BLUE
notificationManager.createNotificationChannel(mChannel)
}
Below are the server logs:
array(1) {
[9]=>
array(2) {
["name"]=>
string(14) "ABL Staff USER"
["fcm_response"]=>
array(2) {
["fields"]=>
array(3) {
["data"]=>
array(4) {
["click_action"]=>
int(2)
["title"]=>
string(19) "Attendance Reminder"
["body"]=>
string(49) "Hi ABL Staff USER, Please mark your attendance ! "
["sound"]=>
string(7) "default"
}
["registration_ids"]=>
array(11) {
[0]=>
string(152) "device_token_1"
}
["notification"]=>
array(4) {
["click_action"]=>
int(2)
["title"]=>
string(19) "Attendance Reminder"
["body"]=>
string(49) "Hi ABL Staff USER, Please mark your attendance ! "
["sound"]=>
string(7) "default"
}
}
Same are working for below android o in foreground and background but not in android o or above
FCM has sent two type of notification
Notification Message
Data Message
Send the data message to show a notification when the app in the background
For more details check the below link
Firebase data message
Are you creating channel by name "bks-channel" ? Looks like you are not creating bks-channel instead you are creating channel by name bks.
Update your create channel method.
#TargetApi(26)
private fun createChannel(notificationManager: NotificationManager) {
val name = "bks-channel"
val description = "bks"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(name, name, importance)
mChannel.description = description
mChannel.enableLights(true)
mChannel.lightColor = Color.BLUE
notificationManager.createNotificationChannel(mChannel)
}