Remove notifications from tray - android

How can I remove all notifications in the notification tray that were sent by my server when the user clicks on one notifiaction?
I have a chatting-app and the user gets a notification for each message (if the app is not in foreground). When the user clicks on one of those notifications the app will be brought to foreground / will be started. After that has happened, I want all other notifications in the notification bar to disappear as well.

No, you dont have to save the ids of all notifications, you can simply call:
NotificationManager nManager = ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
nManager.cancelAll();

Use the following code to cancel a Notification:
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
If you have different notifications that need to be canceled you have to save the ids that you used to create the Notification.

Related

Hide notification from Foreground Service on click notification Action

I have an Alarm App that have foreground service with a Heads-Up Notification and that notification have two actions where one send an intent to the Service and can open an activity depending on the app configuration.
The problem is that when i click on a action that sends the intent to the service the notification doesn't hide. This not seems to occur when the intent opens a Activity
I don't want a foreground service without a Notification, i just want it to hide it back to the Notification Drawer when the intent is sent to the service
Here is the code:
NotificationCompat.Builder(mAlarmApplication, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification_alarm)
.setAutoCancel(false)
.setOngoing(true)
.setVibrate(LongArray(0))
.setContentTitle("Title")
.setContentText("Content")
.addAction(0, dismissActionText, dismissPendingIntent)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(alarmScreenPendingIntent)
.setFullScreenIntent(alarmScreenPendingIntent, true)
Here is the link of the app https://play.google.com/store/apps/details?id=com.garageapp.alarmchallenges.
The problem occurs when alarm start and my current solution is to update the old heads up notification with a new one that is not a heads up but the UX is not a good because on Android 8+ the notification new notification pops up aging
Seems like your Notification is bonded with your Service. If so, then you have to kill the notification in Service
Did you try?
public static void cancelNotification(Context ctx, int notifyId) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
nMgr.cancel(notifyId);
}
You are using .setOngoing(true) which should not be removed while service is working.
.setAutoCancel(true) will also not working with .setOngoing(true).
You have to use .setOngoing(false) to dismiss the notification.
If you or user remove your foreground notification your service will go to background, I think that best work is to not using heads up notification for foreground by not setting its priority to MAX
Use two notifications at same time one in drawer and another heads up:
-The first notification with priority DEFAULT for starting foreground ( auto cancel set to false and ongoing set to true) show this one with startForground()
-The Second notification (Heads up (Priority MAX) auto cancel set to true and on going set to false) for your actions show this with notifyManager.notify()
These two notifications must have different IDs
another solution:
If you want to use one heads up notification with actions for foreground service you may do this:
use a heads up notification with your action buttons for foreground service when the user clicks actions this action must call the foreground service and then the foreground service could call startForeground (with same id) with a new notification with priority set to default, if your notification could not be updated you may need to call stopForeground(true) or notificationManager.cancel(id) first before calling startForeground with new notification. both of these two notifications should has on going set to true and auto cancel set to false
In my opinion the first solution is better than the second because the notification may not update in second solution.
As the documentation says :
A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of ...
android system does not allow you to have a foreground service without notification or a hidden notification. and that's because of user awareness of what is happening in his/her system.
also killing the notification will stop your foreground service.
so you never can have both of the options (foreground service and hidden notification)
a not clear solution for your problem:
when you call action that sends the intent to the service, do this with a mediator activity i mean first open an activity and in the activity send intent to the service.
I hope this solve your problem as you told :
The problem is that when i click on a action that sends the intent to the service the notification doesn't hide. This not seems to occur when the intent opens a Activity

I want to send information through notification

I am making an app for my university, now in which I want to send messages/information about events. How I can send info to them. I tried firebase but, it is working till push notification only. I want if someone clicks on the notification it should open a new activity with whole message/info any code reference will be very helpful.
use the payload to put information into your notification. this could be an event id. The text of your notification is is also set by your server.
Thanks to the payload, your app client knows what event ID was received with the notification (when notification was opened). Just ask your database about information from the received event id from the client and you have all you need.
public void getnotification() {
NotificationManager notificationmgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, your_acitivity.class);
PendingIntent pintent = PendingIntent.getActivities(this, (int) System.currentTimeMillis(), new Intent[]{intent}, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.shadow_fiend)
.setContentTitle(notif_title)//Title of the notification
.setContentText(notif_detail)//Description of the notification
.setContentIntent(pintent)
.setAutoCancel(true)
.build();
notificationmgr.notify(0, notif);
}
When the above function is called a notification is generated and by clicking the notification the user is redirected to a specific activity. In the intent replace the your_acitivity.class to whatever activity you want to be redirected when notification is clicked.
Feel free to comment if I misunderstood your requirements.

Firebase notifications when app is closed

I have implemented Firebase notification in my Android application. When my app is running, notification is displayed with my custom layout, but when application is not running, the notification is displayed with the default layout. How can I change the notification layout to my layout when application is not running. Also, I store shared preferences to let user toggle notifications. But when app is not running the notification is displayed anyways. How can achieve that?
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(SettingsFragment.getReceiceNotification()){ //if user wants to receive notification
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.push_notification_layout);
remoteViews.setImageViewResource(R.id.push_notif_icon,R.mipmap.ic_bird_black);
Intent intent = new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContent(remoteViews);
notificationBuilder.setContentTitle("Radyo Türkkuşu");
notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentIntent(pendingIntent);
remoteViews.setTextViewText(R.id.push_title, "Radyo Türkkuşu");
remoteViews.setTextViewText(R.id.push_context, remoteMessage.getNotification().getBody());
//notificationBuilder.setLights (ContextCompat.getColor(MainActivity.context, R.color.pushColor), 5000, 5000);
notificationManager.notify(0,notificationBuilder.build());
}
}
Your problem is you using it with notification tray.
See this link
Messages with both notification and data payload, both background and foreground. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
If you using {data:"something"}(data-message) with {notification:"something"}(display-message) while your app is in background the data payload will delivered to extras of the intent but not to the onMessageReceived() method.I assume you implement your code for showing notification, so when your app is in foreground onMessageReceived() is trigger and it display the desire notification you want but when it is not onMessageReceived() no get trigger instead android system will handle it with your notification payload. You just have remove {notification:"something"}(display-message/notification tray) from your server side code to always ensure onMessageReceived().
For anyone keep mention onMessageReceived() will always trigger no matter wether it is not foreground or background please visit this link
There are two types of FCM messages
Notification message
Data message
Messages which get sent from Firebase console are Notification message. In order to get message in onMessageReceived() use Data Message. Use below code at server side to send Data Notification message
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
}
Reference https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
Your code should never be triggered when your app is closed or running in the background. See this:Firebase Notification
What you need to do is check how the app start up, tap the notification or tap the launcher icon. To do this, some data should be add into the notification then retrieve them in the first start activity in your app. If you can retrieve them successfully, it means your app is launched by tapping the notification, then you can do what you want to do.

Managing notifications

I'm developing a messaging app that potentially creates multiple notifications. I want it such that these notifications can be updated and deleted when stuff happens.
For example, if I receive a message from A, the notification should say "You have 1 message from A". If another message arrives, it should say "You have 2 messages from A".
Then, if I receive a message from B, it should be a consolidated notification that simply says "You have messages" rather than a separate notification from each sender.
Also, when I click on the notification, it should cancel, and if I click on the user A chat window, any notification from user A should also cancel.
Right now I've implemented the code below for generating notifications:
PendingIntent pendingIntent = PendingIntent.getActivity(context, -1, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder noti = new NotificationCompat.Builder(
context).setContentTitle(context.getResources().getString(R.string.app_name))
.setContentText(notificationMessage)
.setSmallIcon(R.drawable.ic_stat_notify)
setContentIntent(pendingIntent)
setAutoCancel(true)
setWhen(System.currentTimeMillis())
setDefaults(Notification.DEFAULT_ALL);
notificationManager.notify(notifyId, noti.build());
This creates the notification just fine, and cancels it when the user clicks on it. However, I'm unsure how to update notifications, consolidate them, and cancel the appropriate ones. Does anyone know?
Thanks.
You need to use the same Notification ID all the time
public void notify(int id, Notification notification)
id - Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
Just post a new notification with the same ID as the old one, that will replace the old notification with your new one.

NotificationManager.cancel() doesn't work: Notification isn't removed

I've been trying to remove a persistent Notification set by a Service using:
startForeground(1337, notification);
The code I'm using to cancel it:
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(1337); // cancel existing service notification, doesn't take effect
nManager.cancelAll(); //surpluous, but also doesn't take effect
To clarify why I am doing this: the Service starts with a default persistent Notification. When my app runs, it needs to replace this Notification with another. Using notify() on the existing Notification works perfectly, however, I need it to show the ticker text for the new Notification as well. This is why I decided to remove the existing Notification (using the code above), create a new one, and then I call startForeground() again and pass the new Notification to it, so my Service persists.
The problem is that you're issuing the Notification in an indirect way by using startForeground(). You can't just cancel that Notification for the same reason the system insists on you providing a Notification when starting a foreground Service. As long as your foreground Service is running, that Notification will be there.
In most cases, Services really shouldn't be in the foreground. If you can use a normal priority for your Service, then you can start and stop your Notification normally.
If you're actually doing something that truly does require a foreground Service, and if you really want to show the user a ticker text, I believe your only option is to issue another Notification.
You can always remove notification from a foreground service by callng stopForeground(boolean removeNotification). Then a service exits his foregroundState and once again can be killed by the system when the memory is needed.
You could update the notification by passing in an empty Builder.
if(showNotification){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setVisibility(Notification.VISIBILITY_SECRET)
.setSmallIcon(R.mipmap.ic_spotify_white_24dp)
.setTicker("Playing Now")
.setContentTitle("Spotify")
.setContentText("Preview");
return mBuilder;
}else{
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
return mBuilder;
}

Categories

Resources