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)
Related
I am working on a parental control app which notify parent multiple times but when I try to create notification with a background service it generates only one 1.
Here is how I do it:
fun createNotification(parent_name: String, notificationText:String, id: Int){
val MchannelId = channelId+id.toString()
if (Build.VERSION.SDK_INT >= 26) {
val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel(
MchannelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT
)
} else {
TODO("VERSION.SDK_INT < O")
}
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
channel
)
}
val notificationIntent = Intent(this, TabbedActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
id, notificationIntent, 0
)
val notification: Notification = NotificationCompat.Builder(this, "$MchannelId")
.setContentTitle("Hi $parent_name")
.setContentText(notificationText)
.setSmallIcon(R.drawable.icon_child)
//.setContentIntent(pendingIntent)
.build()
startForeground(random_number, notification)
}
My Full-Service Class:
const val TAG2 = "Child Service"
class ParentService: Service() {
val db = FirebaseFirestore.getInstance()
private val channelId = "Notification from Service"
var parent_name = userName
override fun onBind(intent: Intent?): IBinder? = null
//OnBind Function Implementation
init {
Log.d(TAG2, "Started Service!")
}
//onCreate Method Implementation
override fun onCreate() {
super.onCreate()
}
//OnStartCommand Override
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Thread{
while (true){
checkStatus()
Thread.sleep(PARENT_CHECK_TIME)
}
}.start()
return START_STICKY
}
private fun checkStatus() {
var listOfNames = ""
var i = 1
val calendar: Calendar = Calendar.getInstance()
var list = ArrayList<String>()
db.collection(LINKED_CHILDS)
.whereEqualTo(USER_PHONE, userPhone)
.get()
.addOnSuccessListener { documents ->
for (document in documents){
val startTime: Long = calendar.getTimeInMillis()
val diff = startTime - (document.data[ACTIVE_STATUS] as Long)
Log.d("TAG", "Time Difference : $diff")
Log.d("TAG", "${document.data[USER_NAME].toString()}")
if (diff> MAX_GAP_TIME){
Log.d("TAG", "Entered IFF")
list.add(document.data[USER_NAME].toString())
}
}
for (name in list){
listOfNames = listOfNames + "$i. Your child $name is not active\n"
i++
createNotification(parent_name, listOfNames, i)
Log.d("TAG Notification ID:", "ID: $i")
}
Log.d("TAG: ", "$listOfNames")
}
}
fun createNotification(parent_name: String, notificationText:String, id: Int){
val MchannelId = channelId+id.toString()
if (Build.VERSION.SDK_INT >= 26) {
val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel(
MchannelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT
)
} else {
TODO("VERSION.SDK_INT < O")
}
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
channel
)
}
val notificationIntent = Intent(this, TabbedActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
id, notificationIntent, 0
)
val notification: Notification = NotificationCompat.Builder(this, "$MchannelId")
.setContentTitle("Hi $parent_name")
.setContentText(notificationText)
.setSmallIcon(R.drawable.icon_child)
//.setContentIntent(pendingIntent)
.build()
startForeground(id, notification)
}
}
Kinldy let me know how I can create multiple Notifications using this background service. Thank You so much in advance!
Kinldy let me know how I can create multiple Notifications using this background service. Thank You so much in advance!
Kinldy let me know how I can create multiple Notifications using this background service. Thank You so much in advance!
If you create a non-persistent notification, it will show your notifications. The permanent notification will be used for your service to run in the background.
#RequiresApi(Build.VERSION_CODES.O)
private fun createNotification() {
val intent = Intent(this, TabbedActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent =
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
val notification = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.icon_child)
.setContentTitle("Hi $parent_name")
.setContentText(notificationText)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
with(NotificationManagerCompat.from(this)) {
notify(notifManagerId, notification.build())
notifManagerId++
}
parmanentNotification()
}
this is a permanent notification will not be lost and destroyed will keep the service running permanently
private fun parmanentNotification() {
val notification=NotificationCompat.Builder(this,channelId)
.setSmallIcon(R.drawable.icon_child)
.setContentTitle("Hi $parent_name")
.setContentText("Application service running in the background")
.build()
startForeground(1,notification)
}
you aren't creating a common Notification in this scenario, you are running a Service, which must have a foreground representation on screen. So Activity visible or sticked, fixed Notification, and you are showing it
Now you can have much Notifications using similar code, but don't show them using startForeground, instead use NotificationManager, preferably compat version
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(uniqueId, notification);
or just like you are using it already when creating channel inside if: (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).notify(...)
foreground-related Notification is sticky and lives as long as Service works in background, they are "tied". other Notifications may be configured to be sticky or swipeable, also should be posted on some own Channel (per child? per action?). Note that if you show yet another sticky Notification then you have to release it by own through code, just killing Service won't dismiss it as it does with foreground-related Notification
some DOC in here, read carefully, all answers are there
I have been trying to change the sound of the notification but it isn't changing at all.
It is using the default notification in all cases, even when I have assigned the channel.
Please check the codes below and let me know, where I am going wrong.
Created Notification Channel in Application class
class App : Application() {
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
private fun createNotificationChannel() {
val ordersChannelId = "Orders"
val orderSoundUri =
Uri.parse("android.resource://" + applicationContext + "/raw/ordernotification")
val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build()
val VIBRATE_PATTERN = longArrayOf(0,400,800,600,800,800,800,1000)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val ordersChannel =
NotificationChannel(ordersChannelId, "Orders", NotificationManager.IMPORTANCE_HIGH)
ordersChannel.apply {
description = "This is Orders Channel"
setSound(orderSoundUri, attributes)
vibrationPattern = VIBRATE_PATTERN
importance = NotificationManager.IMPORTANCE_HIGH
}
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(ordersChannel)
}
}
Creating Notifications using FireBaseMessagingService
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d("NotificationFire", "From: ${remoteMessage?.data}")
val contentIntent = Intent(applicationContext, OrderInDetailActivity::class.java)
val orderSoundUri = Uri.parse("android.resource://"+applicationContext+"/raw/ordernotification")
val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build()
val VIBRATE_PATTERN = longArrayOf(0, 500)
val contentPendingIntent = PendingIntent.getActivity(
applicationContext,
0,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
remoteMessage?.data?.let {
Log.d("NotificationFire", "Message Notification Data: ${it}")
//Message Services handle notification
val notification = NotificationCompat.Builder(this, "Orders")
.setSmallIcon(R.drawable.biskit_logo)
.setContentTitle(remoteMessage.data.toString())
.setContentText(remoteMessage.data.toString())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(orderSoundUri)
.setVibrate(VIBRATE_PATTERN)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setContentIntent(contentPendingIntent)
.build()
val notificationManager = NotificationManagerCompat.from(this)
Log.d("NotificationFire","Notification")
notificationManager.notify(1,notification)
}
This code is able to display notifications with the default sound only.
In your sound path you appended applicationContext. It will add some random value in your path. Instead you need to add the package name like this below.
Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.FILE_NAME);//Here is FILE_NAME is the name of file that you want to play
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.
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.