Android push dismises after few seconds - android

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()

Related

Notification not triggered on Android Wear OS

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

Android 10: No custom sound in notification

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)
}

How to clear action type notification on action click in android Q?

In android 10, I am using reply type notification. I want to clear that notification on reply action.
To clear the notification I am using this code:
val notificationManager =
context.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(notifyId)
For variable notifyId, I am passing the notification Id.
this code works for all the android versions except android version 10.
This is used to create the reply action:
val replyAction = NotificationCompat.Action.Builder(
R.drawable.ic_send,
btnlable,
getReplyPendingIntent(
notificationId,
title,
msg,
senderName,
action,
apiName,
type,
intentType
)
)
.addRemoteInput(remoteInput)
.setAllowGeneratedReplies(true)
.build()
This is used to create the notification:
val notification = NotificationCompat.Builder(mContext, channelID)
.setSmallIcon(R.drawable.noti_icon)
.setContentTitle(title) //Set the title of Notification
.setContentText(msg) //Set the text for notification
.addAction(replyAction)
.setSound(null)
.setWhen(getTimeMilliSec(timeStamp))
.setLargeIcon(BitmapFactory.decodeResource(mContext.resources, R.drawable.logo))
.setContentIntent(resultPendingIntent)
.build();
notification.flags = Notification.FLAG_AUTO_CANCEL
I don't know where you call .cancel method but I'm doing it on onHandleIntent method of class that inherit from IntentService class and it works:
class ApplicationIntentService() : IntentService("AppIntentService") {
companion object{
const val BIG_TEXT_STYLE_ACTION1_NAME = "big_text_style.action1"
}
override fun onHandleIntent(intent: Intent?) {
var notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (intent?.action == BIG_TEXT_STYLE_ACTION1_NAME) {
notificationManager.cancel(0)
}
}
}
If you did this too, make sure you register your IntentService implementation in Manifest.xml:
<service
android:name=".Services.ApplicationIntentService"
android:exported="false">
</service>

Ongoing Notification not canceling

We're using a jobScheduler to run a periodic weather network call whose results are posted to an ongoing weather notification.
Here's how we create the notification inside the jobService:
private fun createNotification(selectedLocation: City) {
val resultIntent = Intent(context, SplashActivity::class.java)
resultIntent.putExtra(AppConstants.IS_ONGOING, true)
resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
val resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0)
val notificationView = getComplexNotificationView(selectedLocation) ?: return
val notification = NotificationCompat.Builder(context, context.packageName)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSmallIcon(getSmallIconResource(context,
if (settings.isFahrenheitEnabled())
selectedLocation.currentObservation!!.tempF!!
else
selectedLocation.currentObservation!!.tempC!!))
.setVibrate(null)
.setWhen(System.currentTimeMillis())
.setCustomContentView(notificationView)
.setContentIntent(resultPendingIntent)
.setOngoing(true)
.setAutoCancel(false)
.setGroup(AppConstants.NOTIFICATION_GROUP_ONGOING)
.build()
NotificationManagerCompat.from(context).notify(ONGOING_NOTIFY_ID, notification)
}
In our app's settings, the user can disable the ongoing notification. Here's how we're trying to cancel it:
val jobScheduler: JobScheduler? = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler?.cancel(OngoingNotificationJobService.ONGOING_JOB_ID)
NotificationManagerCompat.from(context).cancel(OngoingNotificationJobService.ONGOING_JOB_ID)
The problem:
The cancel call is not clearing the notification. What am I doing wrong?
You have to "NotificationManagerCompat.from(context).cancel()" your previous ONGOING_NOTIFY_ID and not your ONGOING_JOB_ID ;)

How to disable sound/vibration for notification updates on a channel (API 26+)?

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.

Categories

Resources