I have a written a service which fires a notification with an alarm ringtone at a specific time. The notification works as intended, however, the problem is that even after I cancel the notification or click on it from the notification bar, it continues to play the ringtone. Meaning that the notification cancels if I swipe across it, and it opens a pending intent if I click on it. However, the sound/ringtone keeps on playing even after I have performed either of the aforementioned actions (swipe, click).
My code for firing the notification is as follows (it's written in Kotlin):
private fun fireNotification() {
var anotherIntent:Intent=Intent(this,ReminderActivity::class.java)
var p1:PendingIntent= PendingIntent.getActivity(this,0,anotherIntent,0)
val defaultSoundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
var notifyManager: NotificationManager =getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
var notification:Notification=NotificationCompat.Builder(this)
.setContentTitle("Medicine Time")
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(defaultSoundUri)
.setContentText("Time to take your medicine")
.setContentIntent(p1)
.setAutoCancel(true)
.build()
notifyManager.notify(0,notification)
}
Any help in the matter would be greatly appreciated, thanks!
Related
I'm creating a notification with a pendingIntent that opens CallActivity:
NotificationCompat.Builder(context, Constants.CALL_NOTIF_ID)
.setSmallIcon(R.drawable.my_ic)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setSound(null)
.setVibrate(LongArray(0))
.setCategory(NotificationCompat.CATEGORY_CALL)
.setContentIntent(myPendingIntent)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
Im showing this notification while the call is active And clearing it when the call stops with this code:
notificationManager.cancel(Constants.CALL_NOTIF_ID)
Now when I call a device and immediately stop the call, notification appears but it takes 1-2 seconds to disappear. In this short time user can click on notification and can see the CallActivity.
Actually I can make an if check to close activity if there is no call but I don't want to open it in the first place.
So how can I remove the notification immediately without animation (even with reflection)?
I have a foreground service that shows an ongoing notification while running.
Now, it's a streaming app and I want the user to be notified when the stream gets broken (e.g. internet connection dropped). I can't use the main app because the stream can be going while other apps are active. So I need to send a notification to the user from the Foreground Service I use for streaming. The problem is, the notification is not being displayed.
Here's the code I'm currently using:
// registering notification channels
private fun createNotificationChannels() {
val serviceChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID_SERVICE,
NOTIFICATION_CHANNEL_NAME_SERVICE,
NotificationManager.IMPORTANCE_DEFAULT
)
val appChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID_APP,
NOTIFICATION_CHANNEL_NAME_APP,
NotificationManager.IMPORTANCE_HIGH
).apply {
enableVibration(true)
}
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannels(mutableListOf(serviceChannel, appChannel))
}
// starting the service with a required notification
startForeground(
nextInt(100000),
NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_SERVICE)
.setSmallIcon(R.drawable.recording_notification)
.setContentText("Stream is in progress...")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
)
// letting the user know that stream crashed
private fun sendDisconnectNotification() {
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_APP)
.setSmallIcon(R.drawable.disconnected_notification)
.setContentTitle("The stream stopped unexpectedly!")
.setContentText("Please check your internet connection.")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.notify(nextInt(100000), builder.build())
}
I know that sendDisconnectNotification() is being called (put logs there) but the notification never appears.
I was changing so many things that it's hard to specify every piece of code that I tried. But some of the important things I tried were changing the priorities for channels/notifications and sending the notifications in the same/different channels. I also uninstall the app and reboot the phone after every change to make sure the notification settings are applied.
Nothing has been working so far and it got me thinking it's impossible to do. I think that the foreground service only allows one notification to be displayed (the main ongoing one).
Can someone confirm this or give some advice on how to make it work?
I can provide some more code samples if needed.
OK, I’m feeling kinda dumb but it turned out “Do Not Disturb” was turned on on the device. That was the reason the notifications were not visible. Writing this as an answer in case someone like me forgets to turn off DND and finds this SO question.
I'm working on an android application where i need to show a time-sensitive notification in a specific situation.
Normaly our app is running in the background and when the phone is in use the heads up notification is displayed correctly and when the user interacts with it, the correct activity is started.
When the phone is not in use (e.g. locked) the fullScreenIntent works and the correct activity is started.
In the case the user is working with our app at the moment the notification appears, i would like to lead directly to the activity i set as the fullScreenIntent. But at the moment also the head up notification is shown and the activity doesn't start automatically. Is there a way i can make my activity to be started when our app is currently being used by the user?
I build my notification like this and it is used for a foreground service.
val pendingCancelIntent = getCancelPendingIntent()
val pendingFinishIntent = getFinishPendingIntent()
val fullScreenPendingIntent = getFullScreenPendingIntent()
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_icon)
.setContentTitle(getString(R.string.title))
.setContentText(getString(R.string.text))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setFullScreenIntent(fullScreenPendingIntent, true)
notificationBuilder.addAction(
R.drawable.ic_cancel,
getString(R.string.general_cancel),
pendingCancelIntent
)
notificationBuilder.addAction(
R.drawable.ic_finish,
getString(R.string.finish),
pendingFinishIntent
)
notificationBuilder.build()
I am trying to solve an issue that I am experiencing with notifications.
In my app, I am creating a notification (with an indeterminate progress and a randomly generated integer code) when someone clicks a list item to download a file. On the callback of the download, I update the notification to stop the progress, using the same id of the original notification. Clicking a notification is supposed to open the downloads folder on the phone (using a pending intent). All is well at this point.
The issue I am experiencing is when I click on multiple rows to download files, the notifications are grouped. Clicking on the grouped notification results in the app being restarted, and not the pending intent to open. Is this expected behaviour? If not, how can I ensure whenever the user clicks a grouped notification, the downloads folder is opened and the app is not restarted?
This is what I have so far.
Intent downloadFilesIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
PendingIntent pendingIntent = PendingIntent.getActivity(MyActivity.this, MY_CODE, downloadFilesIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), BuildConfig.NOTIFICATION_DOWNLOAD_FILE_CHANNEL)
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("File downloaded")
.setContentIntent(pendingIntent)
.setProgress(0, 0, false)
.setContentText("myFileName.txt");
notificationManager.notify(downloadId, builder.build());
Any ideas what I am doing wrong?
As part of my assignment I want to remove a notification that has been received but not been interacted with after a certain amount of time. This means if the notification is still in the notification tray after this amount of time, the app will delete it automatically.
For foreground notifications this wasn't the issue, as I applied the following code:
void SendNotification(RemoteMessage remotemessage)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
long[] pattern = { 100, 100, 100, 100 };
var notificationBuilder = new Notification.Builder(this)
.SetVibrate(pattern)
.SetSmallIcon(Resource.Drawable.mhu2)
.SetContentTitle(remotemessage.GetNotification().Title)
.SetContentText(remotemessage.GetNotification().Body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager)GetSystemService(Context.NotificationService);
int id = 0;
notificationManager.Notify(id, notificationBuilder.Build());
Handler handler = new Handler(Looper.MainLooper);
long delayInMilliseconds = 5000;
handler.PostDelayed(new Runnable(() => notificationManager.Cancel(id)), delayInMilliseconds);
}
When a notification is received, it will automatically be removed after 5 seconds (debugging purposes). However, as we all know, notifications are not handled the same depending on the state of the app.
This code works for foreground apps, but will never be run when the app is in the background or killed. So when the user receives a notification when the app was not opened or in the background, the notification will not be removed.
I've tried to look into this and saw partial solutions by executing code when overriding the OnDestroy/OnStop/OnPause state, but that still won't help to remove the notification when the app was never opened.
Any suggestions are greatly appreciated!
I just want to post a quick update as I've been able to solve this issue.
Android handles notification differently based on what is provided within the notification. I found out that if the notification is only build with datafields (so no notification body), the OnMessageReceived() will always be fired regardless of the state of the app. The timer that I realised will fire on foreground, background and app closed states. The only time this doesn't work is when the app is forced stopped, but in my context this won't cause issues.