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!
Related
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)
}
}
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'm trying to create the incoming call push notification. When a call event occurs the foreground service with notification starts. I create a channel for it and notification. Here is the code:
The channel settings:
private fun createCallChannelChannel(): NotificationChannel {
val attributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
val importance = NotificationManager.IMPORTANCE_HIGH
return NotificationChannel(CALL_CHANNEL_ID, CALL_CHANNEL_NAME, importance).apply {
description = CALL_CHANNEL_DESCRIPTION
setSound(
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE),
attributes
)
enableLights(true)
enableVibration(true)
}
}
The notification settings:
private fun buildIncomingCallNotification(payload: VoIpCallResponse): Notification {
val remoteView = RemoteViews(packageName, R.layout.notification_call_view)
remoteView.setOnClickPendingIntent(R.id.declineBtn, getDeclinePendingIntent())
remoteView.setOnClickPendingIntent(R.id.acceptBtn, getAcceptPendingIntent(payload))
return NotificationCompat.Builder(this, CALL_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(remoteView)
.setAutoCancel(false)
.build()
}
It works. The notification is being shown. But the problem is notification minimizes to the notifications bar after a few seconds. The goal is to prevent the notification minimization until user decline/ accept the call or the end call event occurs. For example WhatsApp. The incoming call notification stays at the top of the screen for an infinite time. How can I make the same? The importance of my channel is NotificationManager.IMPORTANCE_HIGH and the notification priority is NotificationCompat.PRIORITY_MAX
I have found this page and it has worked
https://developer.android.com/training/notify-user/time-sensitive
val fullScreenIntent = Intent(this, CallActivity::class.java)
val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationBuilder =
NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Incoming call")
.setContentText("(919) 555-1234")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
// Use a full-screen intent only for the highest-priority alerts where you
// have an associated activity that you would like to launch after the user
// interacts with the notification. Also, if your app targets Android 10
// or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
// order for the platform to invoke this notification.
.setFullScreenIntent(fullScreenPendingIntent, true)
and of course use with foregroundService
val incomingCallNotification = notificationBuilder.build()
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 have an application that allows the user to interact with notifications. Here is a simple use case: when the user taps on "Action," the app does some processing and updates the notification to show progress and updates it again to show whether the action was successful or not.
Prior to 26, I was able to set the sound/vibration on individual notifications so once the user click on "Action", the transition to the progress state would not make a sound/vibrate (the behavior that I want) but with 26, it seems like those arguments are no longer respected and the sound/vibration settings are only respected on the channel level.
My initial notification is supposed to make a sound/vibrate but if I am updating an existing (i.e. changing to progress state) then it should not make a sound/vibrate. Is there a way to accomplish that on API 26 and above?
Here is the code for setting up the initial state:
private fun sendNotification() {
val builder = NotificationCompat.Builder(this, "channel_id")
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val intent = Intent(this, MyIntentService::class.java)
val pIntent = PendingIntent.getService(this, ID, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val action = NotificationCompat.Action.Builder(
R.drawable.ic_lock_open_white_24dp,
"Action",
pIntent
).build()
builder.setSmallIcon(R.drawable.ic_home_teal_600_24dp)
.setContentTitle("My Title")
.setContentText("My content text")
.setSound(defaultSoundUri)
.addAction(action)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelName = "My Channel"
val description = "Channel Description"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("channel_id", channelName, importance)
channel.description = description
notificationManager.createNotificationChannel(channel)
}
val manager = NotificationManagerCompat.from(this)
manager.notify(ID, builder.build())
}
And the transition to the progress state (using same id)
private fun updateNotification(notificationId: Int, title: String) {
//This should NOT make sound or vibrate but it does on 26
val builder = NotificationCompat.Builder(this, "channel_id");
builder
.setSmallIcon(R.drawable.ic_home_teal_600_24dp)
.setContentTitle(title)
.setProgress(0, 0, true)
.setContentText("Processing...")
val manager = NotificationManagerCompat.from(this)
manager.notify(notificationId, builder.build())
}
On all API levels, you can disable sound and vibration for notification updates by use setOnlyAlertOnce():
Set this flag if you would only like the sound, vibrate and ticker to be played if the notification is not already showing.
builder.setOnlyAlertOnce(true)
This will ensure that updates to an existing notification won't sound/vibrate.