How do I remove Notification from status bar? - android

I am displaying a Notification in status bar depending up on my condition. Up to this, it is OK.
Now problem in my application is when I come back to application, still the Notification is displayed in the status bar.
I don't want the Notification when I come back from the application. For this give me some suggestions.

I don't have enough rep to add comment so #Commonware . . . it would be more helpful to future readers if you gave more specific details like telling them to use a
"notification id" when they create the notification and use that ID to cancel the notification.
If you give an answer make it complete or at least provide the full details. These posts are not only meant for the OP it helps others who come across this post as well.
like so
final NotificationManager notificationManager = (NotificationManager) getSystemService (NOTIFICATION_SERVICE);
final Notification notification = new Notification(R.drawable.icon,"A New Message!",System.currentTimeMillis());
notification.defaults=Notification.FLAG_ONLY_ALERT_ONCE+Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, AndroidNotifications.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);
notification.setLatestEventInfo(AndroidNotifications.this, title,message, pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
Then to cancel it you call
notificationManager.cancel(NOTIFICATION_ID);
or you can call
notificationManager.cancelAll();

You can cancel() your own Notifications via the NotificationManager. It is up to you to decide when to cancel() it and when to show it.

notificationManager.cancelAll();

private void cancelNotificationInBar() {
NotificationCreator notification = new NotificationCreator(getApplicationContext());
notification.mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (notification.mNotificationManager != null) {
notification.mNotificationManager.cancelAll();
}
}

Related

What is the difference between notificationManager.notify and startForeground in Android?

I am just curious to know what are the differences between NotificationManager.notify and startForeground in Android.
Using NotificationManager.notify you can post as many updates to a notification as you like including adjustments to progress bars via Noticiation.Builder.setProgress in this way you only show one notification to the User, and its the one required by startForeground.
When you want to update a Notification set by startForeground(), simply build a new notication and then use NotificationManager to notify it.
The KEY point is to use the same notification id.
I didn't test the scenario of repeatedly calling startForeground() to update the Notification, but I think that using NotificationManager.notify would be better.
Updating the Notification will not remove the Service from the foreground status (this can be done only by calling stopForground.
Here is an example:
private static final int notif_id=1;
#Override
public void onCreate (){
this.startForeground();
}
private void startForeground() {
startForeground(notif_id, getMyActivityNotification(""));
}
private Notification getMyActivityNotification(String text){
// The PendingIntent to launch our activity if the user selects
// this notification
CharSequence title = getText(R.string.title_activity);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);
return new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher_b3)
.setContentIntent(contentIntent).getNotification();
}
/**
* this is the method that can be called to update the Notification
*/
private void updateNotification() {
String text = "Some text that will update the notification";
Notification notification = getMyActivityNotification(text);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notif_id, notification);
}
You can find more examples and clarification on NotificationManager.notify here
I'd also suggest you to refer this page in order to understand more on startForeground
Usages of startForeground could be found here

Android notification PendingIntent open activity per notification click

I'm currently doing some notifications for my app. Now I've successfully created a notification but problem is that each of my notification doesn't pass different extras on click.
Well what happen is that I only have a loop that calls the createNotification method per loop and also I assign different ID's for those for the notification to appear in different stack.
here's my code:
private void createNotification(String record_name, String file_path, String status, int id) {
/*must pass:
* record_name, (get the record name in DB using the id create a new query method)
* record_status, (simple part just match if equivalent to ready to download for the JSON data then show notif if true)
* record_path *full path* (this one can be get using the record name itself add the path and extension name)*/
/*this will jump from the current activity into the target activity class just do some workarounds here*/
Intent intent = new Intent(this, RecordEditActivity.class);
intent.putExtra("record_name", record_name);
intent.putExtra("record_path", file_path);
intent.putExtra("record_status", status);
PendingIntent pIntent = PendingIntent.getActivity(this,0, intent, 0);
/*build the notification here this is only supported for API 11. Since we've targeted API 11 there will be no problem on this*/
NotificationCompat.Builder notify = new NotificationCompat.Builder(this)
.setContentTitle(record_name + " is ready for download")
.setContentText("Click to view or download recording")
.setAutoCancel(true)
.setSmallIcon(R.drawable.notif_icon)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher))
.setTicker("Echo: your file is ready for download")
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT<16){
/*build notification for HoneyComb to ICS*/
notificationManager.notify(id, notify.getNotification());
}if(Build.VERSION.SDK_INT>15){
/*Notification for Jellybean and above*/
notificationManager.notify(id, notify.build());
}
}
I think the problem is in the PendingIntent part since I don't know which flags should I use for this but I'm not that sure about it.
Got it! what needed is for me to assign an ID for my pendingIntent requestCode what I did is assign the same ID I used for my notificationManager.
More info here.
Just use this one line of code-
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
And for more detail see this answer:
GCM android Push Notification shows old message always. Intent received incorrect

How to add my app's icon into the status bar when my app is running?

I tried to use the Notification.Builder and the Notification classes.
I tried using this code :
Notification notification = new Notification.Builder(this).build();
notification.icon = R.drawable.ic_launcher;
notification.notify();
but it seems useless.
I only want my app's icon to be added next to the battery icon,wifi icon and 3g icons.. Any way to do that? I appreciate your help.
You have to call the method build() after you have finished describing your notification. Check out the Android reference for an example.
Basically, you have to change your code to the following:
Context context = getApplicationContext();
NotificationCompat.Builder builder = new NotificationCompat.Builder(context )
.setSmallIcon(R.drawable.ic_launcher);
Intent intent = new Intent( context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, mID , intent, 0);
builder.setContentIntent(pIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = builder.build();
mNotificationManager.notify(mID, notif);
Note: this code will only allow to show your icon in the notification bar. If you want it to persist there, you will have to use FLAG_ONGOING_EVENT
You can add your app icon for status bar notification. Try this one
Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher).build();

Notification FLAG_ONLY_ALERT_ONCE not working on 2.1

I'm trying to create a notification when an alarm fires. No problem so far.
A notification is shown. The problem is on my device (2.1 Update 1) it is displayed as an ongoing notification. While on another device (2.2) it is working fine and is actually shown as a one time only notification. Has anyone experienced this behaviour, and more important has anyone been able to fix it. It seems like 2.1 is not respecting the FLAG_ONLY_ALERT_ONCE or any flags for that mather. See my code below. Any help would be appreciated.
public class AlarmHandler extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
Debug.log("Alarm notification received");
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = intent.getStringExtra("AlarmType");
CharSequence message = intent.getStringExtra("AlarmType");
Intent newIntent = new Intent(context, Splashscreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, intent.getIntExtra("RequestCode", 0),
newIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notif = new Notification(R.drawable.icon,
null, System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
Debug.log("flags: "+notif.flags);
Debug.log("Defaults: "+notif.flags);
nm.notify(intent.getIntExtra("RequestCode", 0), notif);
}
}
Please find below values and definition for each one. Hope you can get idea from this.
FLAG_ONLY_ALERT_ONCE = 8
Definition : It should be set if you want the sound and/or vibration play each time the notification is sent, even if it has not been canceled before that.
FLAG_ONGOING_EVENT = 2
Definition: It should be set if this notification is in reference to something that is ongoing, like a phone call. It should not be set if this notification is in reference to something that happened at a particular point in time, like a missed phone call.
FLAG_AUTO_CANCEL = 16
Definition: The notification should be canceled when it is clicked by the user
Also you if you want to cancel the notification manually then use below code
nm.cancel(id);

Android: remove notification from notification bar

I have created an application and with an event I manage to add notification in android notification bar. Now I need sample how to remove that notification from notification bar on an event ??
You can try this quick code
public static void cancelNotification(Context ctx, int notifyId) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
nMgr.cancel(notifyId);
}
This is quite simple. You have to call cancel or cancelAll on your NotificationManager. The parameter of the cancel method is the ID of the notification that should be canceled.
See the API: http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)
You can also call cancelAll on the notification manager, so you don't even have to worry about the notification ids.
NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
EDIT : I was downvoted so maybe I should specify that this will only remove the notification from your application.
this will help:
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancelAll();
this should remove all notifications made by the app
and if you create a notification by calling
startForeground();
inside a Service.you may have to call
stopForeground(false);
first,then cancel the notification.
simply set setAutoCancel(True) like the following code:
Intent resultIntent = new Intent(GameLevelsActivity.this, NotificationReceiverActivityAdv.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
GameLevelsActivity.this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext()).setSmallIcon(R.drawable.icon)
.setContentTitle(adv_title)
.setContentText(adv_desc)
.setContentIntent(resultPendingIntent)
//HERE IS WHAT YOY NEED:
.setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(547, mBuilder.build());`
If you are generating Notification from a Service that is started in the foreground using
startForeground(NOTIFICATION_ID, notificationBuilder.build());
Then issuing
notificationManager.cancel(NOTIFICATION_ID);
does't work canceling the Notification & notification still appears in the status bar. In this particular case, you will solve these by 2 ways:
1> Using stopForeground( false ) inside service:
stopForeground( false );
notificationManager.cancel(NOTIFICATION_ID);
2> Destroy that service class with calling activity:
Intent i = new Intent(context, Service.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
if(ServiceCallingActivity.activity != null) {
ServiceCallingActivity.activity.finish();
}
context.stopService(i);
Second way prefer in music player notification more because thay way not only notification remove but remove player also...!!
A short one Liner of this is:
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
Or to cancel all notifications is:
NotificationManagerCompat.from(context).cancelAll()
Made for AndroidX or Support Libraries.
Please try this,
public void removeNotification(Context context, int notificationId) {
NotificationManager nMgr = (NotificationManager) context.getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancel(notificationId);
}
Use the NotificationManager to cancel your notification. You only need to provide your notification id
mNotificationManager.cancel(YOUR_NOTIFICATION_ID);
also check this link
See Developer Link
NotificationManager.cancel(id) is the correct answer. Yet you can remove in Android Oreo and later notifications by deleting the whole notification channel. This should delete all messages in the deleted channel.
Here is the example from the Android documentation:
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "my_channel_01";
mNotificationManager.deleteNotificationChannel(id);
It will help you
private var notificationManager = NotificationManagerCompat.from(this)
notificationManager.cancel("your_notification_id")
If you start notification foreground like this
startForeground("your_notification_id",notification.build())
Then you should stop foregroundservice also
notificationManager.cancel("your_notification_id")
stopForeground(true)
On Android API >=23 you can do somehting like this to remove a group of notifications.
for (StatusBarNotification statusBarNotification : mNotificationManager.getActiveNotifications()) {
if (KEY_MESSAGE_GROUP.equals(statusBarNotification.getGroupKey())) {
mNotificationManager.cancel(statusBarNotification.getId());
}
}
Just call ID:
public void delNoti(int id) {((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(id);}

Categories

Resources