Cancelar notificación dinámica en Android cuando se selecciona la notificación

Supongamos que estoy creando una aplicación de Android que es como una aplicación de SMS. Los requisitos son los siguientes:

  1. El usuario puede recibir múltiples notificaciones, cada una con un ID dinámico de tipo int.
  2. Cuando se selecciona una notificación, carga una actividad que muestra un mensaje correspondiente (el SMS).
  3. La notificación única que se seleccionó debe descartarse automáticamente.

Mi idea de cómo manejar esto era usar putExtra para agregar el ID entero a la intención, que entonces sería accesible desde la intención dentro de la actividad que carga, lo que descartaría la notificación que lo llamó.

Para mi caso de prueba, he aquí las especificaciones:

  1. Eventualmente se generarán notificaciones a partir de un servicio, por ahora se generan cuando el usuario de prueba presiona un botón.
  2. Cuando se selecciona una notificación, la actividad llamada toasts el mensaje, a continuación, intenta descartar la notificación. (En aras de la visibilidad)

Aquí están mis problemas:

  1. Cuando se selecciona la primera notificación, es correcta. Se desestima la notificación.
  2. Cuando se selecciona cada notificación sucesiva, se muestra el ID de la primera notificación y no se descarta nada.
  3. Soy un novato de Java, más acostumbrado a los lenguajes de scripting (como Perl, PHP, etc) 🙂

Aquí está mi fuente:

<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "fill_parent" android:layout_height = "fill_parent" > <Button android:id="@+id/create_notification" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:text = "Create new notification" /> 

 package org.test.notifydemo; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.util.Random; public class aRunNotificationDemo extends Activity { private NotificationManager mNotificationManager; @Override public void onCreate( Bundle icicle ) { super.onCreate( icicle ); setContentView( R.layout.run_notify_demo ); mNotificationManager = (NotificationManager) getSystemService( aRunNotificationDemo.NOTIFICATION_SERVICE ); int close_notify_id = getIntent().getIntExtra( "notification_id", 0 ); if ( close_notify_id != 0 ) { Toast.makeText( aRunNotificationDemo.this, "Dimissing this notification: " + Integer.toString(close_notify_id), Toast.LENGTH_SHORT ).show(); mNotificationManager.cancel( close_notify_id ); } findViewById( R.id.create_notification ).setOnClickListener( new MyButtonListener() ); } private class MyButtonListener implements Button.OnClickListener { public void onClick( View my_view ) { Random randGen = new Random(); int notify_id = randGen.nextInt(); int icon = R.drawable.icon_notification_01; CharSequence tickerText = Integer.toString(notify_id) + " New SMS!"; long when = System.currentTimeMillis(); Notification my_notification = new Notification(icon, tickerText, when); Context context = getApplicationContext(); CharSequence contentTitle = Integer.toString(notify_id) + " New SMS Available!"; CharSequence contentText = Integer.toString(notify_id) + " There is a new SMS available."; Intent notificationIntent = new Intent( aRunNotificationDemo.this, aRunNotificationDemo.class ); notificationIntent.putExtra( "notification_id", notify_id ); PendingIntent contentIntent = PendingIntent.getActivity( aRunNotificationDemo.this, 0, notificationIntent, 0 ); my_notification.setLatestEventInfo( context, contentTitle, contentText, contentIntent ); mNotificationManager.notify( notify_id, my_notification ); } } } 

Cuando se crea una actividad, se onCreate() su método onCreate() . La próxima vez que se muestre el método no es necesariamente llamado. Intente mover el código que elimina la notificación al método onResume() . Familiarícese con el ciclo de vida de la actividad.

Y por cierto es más fácil de lo que piensas:

http://developer.android.com/reference/android/app/Notification.html#FLAG_AUTO_CANCEL

 my_notification.flags |= Notification.FLAG_AUTO_CANCEL; 

Ponga el código de arriba al crear una Notification .

  • Android: ¿Cómo puedo poner mi notificación encima del área de notificación?
  • ¿Es una práctica común preguntar a los usuarios si desean recibir notificaciones push?
  • Notificación de Android para intentar borrarlo
  • Android: guarda el sonido como tono de llamada y notificación
  • El icono de notificación de Lollipop es demasiado pequeño
  • ¿Cómo puedo añadir el sonido de notificación de mi aplicación a la lista de sonidos de notificación?
  • ¿Por qué los iconos establecidos con Notification.Builder.setSmallIcon en Android Lollipop muestran como un cuadrado blanco?
  • ¿Cómo mostrar la notificación de Android cada 48 horas?
  • Apertura del navegador en la notificación push
  • Controles del reproductor de medios en la notificación
  • Notificaciones push iOS y código nativo cliente-cliente de Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.