2010-08-13 56 views
28

He leído muchos ejemplos de cómo crear mensajes de notificación. Lo que quería lograr, es que la notificación se ejecutará mediante un widget, me gustaría el intento de notificación al hacer clic para borrarlo cuando el usuario hace clic en él. No tengo una actividad a la que volver. La notificación para mi propósito simplemente notificará, nada más. Entonces, ¿cuál sería el código de un intento que simplemente se borra/cancela solo? El siguiente código es una actividad iniciada por un botón (código de botón no incluido) la notificación se iniciará por un servicio en segundo plano.intento de notificación de Android para borrarlo

CharSequence title = "Hello"; 
CharSequence message = "Hello, Android!"; 
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); 

Gracias

Respuesta

1

La única forma que veo de hacer esto es tener Intent punto sus Notification 's de un fondo Service. Cuando se inicia este servicio, se borrará el Notification dado usando NotificationManager.cancel(int id). El Service se detendría. No es bonito, y no sería fácil de implementar, pero no puedo encontrar ninguna otra forma de hacerlo.

+0

Si desea que el código para cancelar la notificación utilice el 'NOTIFICATION_ID' al cancelar la llamada. – Pentium10

+0

Sí, estaría llamando desde un botón, pero me gustaría llamarlo desde el código cuando el usuario selecciona la notificación. – John

+0

Solución de Works-for-me, aunque un poco desordenada (se escribirá un servicio adicional). Pero en el Servicio tengo acceso al Intento de llamada en el cual se puede dar la ID de notificación como argumento. –

73

Salida FLAG_AUTO_CANCEL

poco que-ORED modo bit en el campo de los indicadores que deben ajustarse si la notificación debe ser cancelada cuando se hace clic por el usuario.

EDIT:

notification.flags |= Notification.FLAG_AUTO_CANCEL; 
+0

Mi código ya está usando FLAG_AUTO_CANCEL, pero en realidad la notificación no se va al hacer clic. – John

+17

Su código usa el campo incorrecto (pone en valores predeterminados), necesita hacerlo en modo bit, o en el campo de indicadores de esta manera: 'notification.flags | = Notification.FLAG_AUTO_CANCEL;' – Pentium10

+2

Gracias notification.flags | = Notification.FLAG_AUTO_CANCEL; Trabajó. – John

19

Establecer las banderas en vez de notification.flags notification.defaults.

Ejemplo:

notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL; 
1
/** 
     Post a notification to be shown in the status bar. 
     Obs.: You must save this values somewhere or even pass it as an extra through Intent to use it later 
*/ 
notificationManager.notify(NOTIFICATION_ID, notification); 

/** 
     Cancel a previously shown notification given the notification id you've saved before 
*/ 
notificationmanager.cancel(NOTIFICATION_ID); 
+0

cancelar la notificación inmediatamente después de 'notify()' hace que la notificación no se muestre en absoluto. – Aryo

10

Si está utilizando NotificationCompat.Builder (una parte de android.support.v4) entonces simplemente llamar al método de su objeto setAutoCancel

NotificationCompat.Builder builder = new NotificationCompat.Builder(context); 
builder.setAutoCancel(true); 

Algunos chicos estaban informando que setAutoCancel() no lo hicieron trabaje para ellos, por lo que puede intentarlo también

builder.build().flags |= Notification.FLAG_AUTO_CANCEL; 
+0

gracias por los ans :) – Nevaeh

1

Usando setContentIntent debe resolver su problema:

.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)); 

Por ejemplo:

NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this) 
     .setSmallIcon(R.drawable.notification_icon) 
     .setContentTitle("title") 
     .setAutoCancel(true) 
     .setContentText("content") 
     .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)); 
NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
notificationManager.notify(0, mBuilder.build()); 

A menudo, es posible que desee dirigir al usuario el contenido relevante y así podría sustituir 'nueva Intención()' con algo más

Cuestiones relacionadas