2010-08-29 28 views
131

He creado una aplicación y con un evento me las arreglé para agregar notificaciones en la barra de notificaciones de Android. ¿Ahora necesito una muestra de cómo eliminar esa notificación de la barra de notificaciones en un evento?Android: eliminar la notificación de la barra de notificaciones

+1

posible duplicado de [Quitar el icono de notificación de la barra de estado] (http://stackoverflow.com/questions/2839727/remove-the-notification- icon-from-the-status-bar) – rds

+0

por fragmento de código, ver [Eliminar Notiication] (http://androidtrainningcenter.blogspot.in/2013/04/removing-status-bar-notification-from.html) – Sameer

Respuesta

141

Esto es bastante simple. Debe llamar al cancel o cancelAll en su NotificationManager. El parámetro del método de cancelar es la ID de la notificación que debe cancelarse.

Ver la API: http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)

+0

Gracias Roflcoptr :) Lo encontré aquí: http://stackoverflow.com/questions/2839727/remove-the-notification-icon-from-the-status-bar – Nezir

+2

private static final int MY_NOTIFICATION_ ID = 1234; String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager; mNotificationManager = (NotificationManager) getSystemService (ns); mNotificationManager.notify (MY_NOTIFICATION_ID, notificación); El código de ejemplo no está completo. Depende de cómo haya creado su notificación. Solo asegúrese de usar la misma ID para cancelar su notificación como la utilizó cuando creó su notificación. Para cancelar: mNotificationManager.cancel (MY_NOTIFICATION_ID); – Nezir

+0

¡Has ahorrado el día! Es un placer leer a personas como tú, a pesar de que no son respuestas complejas a problemas complejos, personas como tú nos ayudan mucho en tiempos difíciles. Muchas gracias. –

184

Puede probar este código rápido

public static void cancelNotification(Context ctx, int notifyId) { 
    String ns = Context.NOTIFICATION_SERVICE; 
    NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns); 
    nMgr.cancel(notifyId); 
} 
+14

Esta debería ser la respuesta correcta porque es simple, correcta y va directamente al grano. – ZeroTek

+1

Hola, esta es la respuesta correcta. Pero la Bandeja de notificaciones permanece visible. ¿Hay alguna forma de ocultarlo también? Por ejemplo, tengo dos acciones asociadas con la Notificación: cancelar y listo. Cuando se toman cualquiera de estas acciones, elimino la notificación. Pero al hacerlo, solo elimina la notificación, pero la bandeja de notificaciones permanece visible. –

1

Uso del NotificationManager cancelar su notificación. Solo debe proporcionar su ID de notificación

mNotificationManager.cancel (YOUR_NOTIFICATION_ID);

también comprobar este enlace See Developer Link

50

También puede llamar cancelAll en el gestor de notificaciones, por lo que ni siquiera tiene que preocuparse de los identificadores de notificación.

NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
notifManager.cancelAll(); 

EDIT: Estaba desvalorizado, así que tal vez debería especificar que esto solo eliminará la notificación de su aplicación.

+2

gracias ahorró tiempo .. – Reshma

+0

no hay administrador de notificaciones para primer plano: 'startForeground (NOTIFICATION_ID, mNotification);' – user924

9

basta con establecer setAutoCancel (verdadero) como el siguiente código:

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());` 
+3

Esto funciona solo si toca la notificación directamente. Al tocar en la acción (como aquí: https://pl.vc/1gvrli) no se elimina la notificación. – baris1892

+0

Esto no es lo que se preguntó. La pregunta: "¿Necesito una muestra de cómo eliminar esa notificación de la barra de notificaciones en un evento?" – David

5

Si va a generar notificación de un servicio que se inicia en el primer plano usando

startForeground(NOTIFICATION_ID, notificationBuilder.build()); 

Luego de emitir

notificationManager.cancel(NOTIFICATION_ID); 

no funciona cancelando la notificación & notificación todavía aparece en la barra de estado. En este caso particular, usted va a resolver éstos por 2 maneras:

1> Uso stopForeground (falso) en el interior del servicio:

stopForeground(false); 
notificationManager.cancel(NOTIFICATION_ID); 

2> destruir esa clase de servicio con la actividad llamando al:

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

Segunda manera preferida en notificación al reproductor de música más porque de esa manera no solo se elimina la notificación sino que se eliminan p capa también ... !!

+0

Gracias por su respuesta! Usando 'stopForeground (verdadero); manager.cancelAll(); '¡es lo que me solucionó! – Sky

3

esto ayudará a:

NotificationManager mNotificationManager = (NotificationManager) 
      getSystemService(NOTIFICATION_SERVICE); 
mNotificationManager.cannelAll(); 

y si crea una notificación llamando

startForeground(); 

dentro de un Service.you puede tener que llamar

stopForeground(false); 

primero, luego cancele la notificación.

1

En Android API> = 23 puedes hacer algo así para eliminar un grupo de notificaciones.

for (StatusBarNotification statusBarNotification : mNotificationManager.getActiveNotifications()) { 
     if (KEY_MESSAGE_GROUP.equals(statusBarNotification.getGroupKey())) { 
      mNotificationManager.cancel(statusBarNotification.getId()); 
     } 
    } 
0

NotificationManager.cancel(id) es la respuesta correcta. Sin embargo, puede eliminar en Android Oreo y notificaciones posteriores eliminando todo el canal de notificación. Esto debería eliminar todos los mensajes en el canal eliminado.

Aquí está el ejemplo de la Android documentation:

NotificationManager mNotificationManager = 
     (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
// The id of the channel. 
String id = "my_channel_01"; 
mNotificationManager.deleteNotificationChannel(id); 
Cuestiones relacionadas