I am trying to show a custom notification when I get a push notification from firebase, when the app is in background.
When the app is in background, the log messages START and END gets printed but does not show the notification on Android which I created as customNotification.
This is how I created a notification.
Could you please suggest what should be corrected please
override fun onMessageReceived(message: RemoteMessage) {
Log.d("FCMService", "onMessageReceived START")
//super.onMessageReceived(message)
// Get the layouts to use in the custom notification
val notificationLayout = RemoteViews(packageName, R.layout.plugin_requires_approval_notification_small)
val notificationLayoutExpanded = RemoteViews(packageName, R.layout.plugin_requires_approval_notification_large)
// Apply the layouts to the notification
val customNotification = NotificationCompat.Builder(this, "FcmService")
.setSmallIcon(R.mipmap.ic_launcher)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.build()
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, customNotification)
Log.d("FCMService", "onMessageReceived END")
}
Thanks in advance
R
EDIT
it is fixed now, the issue was with the CHANNEL_ID I provided.
for reference channelID should be the one used in the notificationChannel() function which looks like the bellow code, this is in the project App class.
private fun createNotificationChannels() {
// Do this only on API 26+ because the NotificationChannel
// class is new and not in the AndroidX library
if (SDK_INT >= O) {
val caInfoNotifChannel = NotificationChannel(CaInfoProcessingService.NOTIFICATION_CHANNEL_ID,
getString(R.string.ca_info_service_notif_channel_name),
IMPORTANCE_LOW).apply {
description = getString(R.string.ca_info_service_notif_channel_desc)
}
// Register the channel with the system
getSystemService<NotificationManager>()?.createNotificationChannel(caInfoNotifChannel)
}
}
Related
I have been getting a blank/grey notification icon on some Android devices (Pixel 2 XL and Pixel 5 - both Android 11), but it shows up fine on other Android devices I tested on (Huawei P20 & P30 - both Android 10). Has anyone else come across this anomaly?
This is what I tried:
I have ensured all icon sizes follow the defined bitmap
densities using the Android Asset Studio.
I also added the the .setColorized() method to the
Notification.Builder object as it was previously missing in the
code, but that made no difference at all. I have included my
notification code below:
private fun sendNotification(title: String?, message: String?, intent: Intent) {
val pendingIntent = PendingIntent.getActivity(
this,
0 /* Request code */,
intent,
PendingIntent.FLAG_ONE_SHOT
)
// With the default notification channel id the heads up notification wasn't displayed
val channelId = getString(R.string.heads_up_notification_channel_id)
val notificationBuilder =
NotificationCompat.Builder(this, channelId).setSmallIcon(R.mipmap.ic_stat_ic_notification)
.setAutoCancel(true)
.setColorized(true)
.setColor(ContextCompat.getColor(this, R.color.color_orange))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
if (title != null) {
notificationBuilder.setContentTitle(title)
}
if (message != null) {
notificationBuilder.setContentText(message).setStyle(
NotificationCompat.BigTextStyle()
.bigText(message)
)
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
"Test",
NotificationManager.IMPORTANCE_HIGH
)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(Random.nextInt()/* ID of notification */, notificationBuilder.build())
}
I have had a similar Issue before. In my case the problem was the icon that I tried to use. I used a non-PNG file for the icon of the notification. When I switch it to PNG format, the nofication worked normally for all devices I tested.
If you are not using Png format for the icon , you can try this way.
Also, the problem can be the size of your icon in android reference website it is stated that
Set the small icon to use in the notification layouts. Different classes of devices may return different sizes.
Also see this guiadeline for Keyline Shapes
I tested on android 9,10,11. It's working fine.
In android studio, select image asset -> click icon type -> click Notification icons like this notification icon creation in android studio or create vector asset.both worked.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scrolling)
sendNotification("Hello","thinking of refering friend?",intent);
}
private fun sendNotification(title: String?, message: String?, intent: Intent) {
val pendingIntent = PendingIntent.getActivity(
this,
0 /* Request code */,
intent,
PendingIntent.FLAG_ONE_SHOT
)
// With the default notification channel id the heads up notification wasn't displayed
val channelId = getString(R.string.heads_up_notification_channel_id)
val notificationBuilder =
NotificationCompat.Builder(this, channelId).setSmallIcon(R.drawable.abcd)
.setAutoCancel(true)
.setColorized(true)
.setColor(ContextCompat.getColor(this, R.color.color_orange))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
if (title != null) {
notificationBuilder.setContentTitle(title)
}
if (message != null) {
notificationBuilder.setContentText(message).setStyle(
NotificationCompat.BigTextStyle()
.bigText(message)
)
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
"Test",
NotificationManager.IMPORTANCE_HIGH
)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(Random.nextInt()/* ID of notification */, notificationBuilder.build())
}
}
let me know .
I have make notification fun outside the override onCreat fun
when i test the app i got the notifications but it doesn't show up, i only get vibration on my phone
while when i try the same code in an individual project just to check the notification fun it works correctly
and when i try to move the fun of notifications inside the onCreat fun and same problem
i tried to put the fun inside or outside the override fun but its not working
fun notifyMe(){
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val intent = Intent(this#MapsActivity, LauncherActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this#MapsActivity,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = NotificationChannel(channelId,description,NotificationManager.IMPORTANCE_HIGH)
notificationChannel.enableLights(true)
notificationChannel.enableVibration(true)
notificationChannel.lightColor = Color.GREEN
notificationManager.createNotificationChannel(notificationChannel)
buildder = Notification.Builder(this#MapsActivity,channelId)
.setContentTitle("NEAR")
.setContentText("YOU ARE NEAR ")
.setSmallIcon(R.drawable.ic_launcher_round)
.setLargeIcon(BitmapFactory.decodeResource(this#MapsActivity.resources,R.drawable.ic_launcher))
.setContentIntent(pendingIntent)
}else{
buildder = Notification.Builder(this#MapsActivity)
.setContentTitle("Distinatios")
.setContentText("YOU ARE near ")
.setSmallIcon(R.drawable.ic_launcher_round)
.setLargeIcon(BitmapFactory.decodeResource(this#MapsActivity.resources,R.drawable.ic_launcher))
.setContentIntent(pendingIntent)
}
notificationManager.notify(1234,buildder.build())
}
i expect to get simple notification
now i got only the vibration of the notification
You may be able to simplify this by using NotificationCompact.Builder and let it handle making your notification compatible with different OS versions. In my application, I also included setPriority(NotificationCompat.PRIORITY_HIGH) on the builder call. If those don't work, I would try commenting out .setLargeIcon(...) just to ensure that it isn't some issue with parsing the image.
Hope it helps!
I am trying to make my button send a notification to the phone, so I made a function sendNotification in my MainActivity.kt class.
This is code from the Android Docs which I put into a function:
fun sendNotification(view: View){
with(NotificationManagerCompat.from(this)) {
notify(notificationId, mBuilder.build())
}
}
This is the rest of the code if it helps somehow:
val notificationId = 1
val channel_id = "channel"
fun createNotificationChannel() {
// 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 name = getString(R.string.channel_name)
val descriptionText = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(channel_id, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
var mBuilder = NotificationCompat.Builder(this, channel_id)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hello from my first notification!")
.setContentText("Aayyee wassup?")
.setStyle(NotificationCompat.BigTextStyle().bigText("Aayyee wassup this is some longer text..."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
Now, when I try to set the onClick Attribute in activity_main.xml I get
this.
When I click the sendNotification function with the [MainActivity] it just switches to the one above. When running the app nothing happens when I click the button.
Please excuse the rough code as I am a beginner and most of this code is from the Android Docs. Ask for more info if needed. Any help is appreciated. Thanks :)
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.
I'm using firebase notifications. This is FirebaseMessagingService:
class mFirebaseMessagingService : FirebaseMessagingService() {
private lateinit var notification: Notification
private val badgeCount = 3 //value to show in badge
override fun onMessageReceived(remoteMessage: RemoteMessage) {
sendNotification(remoteMessage.notification.body)
}
private fun sendNotification(message: String) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val builder = NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.img)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.img))
.setContentTitle(this.getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
notification = builder.build()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notification)
ShortcutBadger.applyNotification(applicationContext, notification, badgeCount) //trying to use it
}
}
I need to set icon badge count to my value, but Firebase set it to count of notifications. I'm trying to use ShortcutBadger library but it doesn't work well with firebase notifications. Works only if notifications creating programmatically (by the button for example). Any idea?