2012-09-30 19 views
22

¿Hay alguna forma en Android de detectar cuándo un usuario desliza una notificación hacia la izquierda y la elimina? Estoy usando un alarmmanager para establecer una alerta de repetición y necesito que mi alerta de repetición se detenga cuando el usuario cancela la notificación. Aquí está mi código:¿Cómo detectar si una notificación ha sido descartada?

Configuración de la alerta de repetición:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), repeatFrequency, displayIntent); 

Mi código de notificación:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    //Get the notification ID. 
    int notifID = getIntent().getExtras().getInt("Reminder_Primary_Key"); 

    //Get the name of the reminder. 
    String reminderName = getIntent().getExtras().getString("Reminder_Name"); 

    //PendingIntent stores the Activity that should be launched when the user taps the notification. 
    Intent i = new Intent(this, ViewLocalRemindersDetail.class); 
    i.putExtra("NotifID", notifID); 
    i.putExtra("notification_tap", true); 

    //Add FLAG_ACTIVITY_NEW_TASK to stop the intent from being launched when the notification is triggered. 
    PendingIntent displayIntent = PendingIntent.getActivity(this, notifID, i, Intent.FLAG_ACTIVITY_NEW_TASK); 

    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    Notification notif = new Notification(R.drawable.flag_red_large, reminderName, System.currentTimeMillis()); 

    CharSequence from = "Here's your reminder:"; 

    CharSequence message = reminderName;   
    notif.setLatestEventInfo(this, from, message, displayIntent); 

    //Pause for 100ms, vibrate for 250ms, pause for 100ms, and vibrate for 500ms. 
    notif.defaults |= Notification.DEFAULT_SOUND; 
    notif.vibrate = new long[] { 100, 250, 100, 500 }; 
    nm.notify(notifID, notif); 

    //Destroy the activity/notification. 
    finish(); 

} 

Sé que necesito para llamar alarmManager.cancel(displayIntent) con el fin de cancelar mi alarma de repetición. Sin embargo, no entiendo dónde poner este código. Necesito cancelar la alerta de repetición SOLAMENTE cuando el usuario ha tocado la notificación o la ha descartado. ¡Gracias por tu ayuda!

+2

No importa, encontré mi respuesta aquí: http://stackoverflow.com/questions/8811876/notification-deleteintent-does-not-work. – NewGradDev

Respuesta

15

Creo que Notification.deleteIntent es lo que estás buscando. El doctor dice:

la intención de ejecutar cuando la notificación se descartó explícitamente por el usuario, ya sea con el botón "Borrar todo" o al golpear a la basura de forma individual. Esto probablemente no debería iniciar una actividad ya que varios de ellos se enviarán al mismo tiempo.

+7

¿Cómo? ¿Puedes ayudar proporcionando un código de muestra? –

+0

Esta solución me ayudó: https://stackoverflow.com/a/14723652/563509 – masterwok

0

Para todas esas personas futuras, puede registrar un receptor de difusión para escuchar los avisos de eliminación de notificaciones.

Crear un nuevo receptor de radiodifusión:

public class NotificationBroadcastReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 

     if (action == null || !action.equals(Config.NotificationDeleteAction)) { 
      return; 
     } 

     // Do some sweet stuff 
     int x = 1; 
    } 
} 

Registre el receptor de radiodifusión dentro de su clase de aplicación:

"Si sus objetivos de aplicaciones de nivel API 26 o superior, no se puede utilizar el manifiesto para declarar un receptor para la mayoría de las transmisiones implícitas (emisiones que no se dirigen específicamente a su aplicación) ".

Android Documentation.

registerReceiver(
     new NotificationBroadcastReceiver(), 
     new IntentFilter(Config.NotificationDeleteAction) 
); 

probablemente notó la variable estática Config.NotificationDeleteAction. Este es un identificador de cadena único para su notificación. Por lo general sigue el siguiente espacio de nombres {} {} actionName convención:

you.application.namespace.NOTIFICATION_DELETE

Establecer la intención de borrar en la página de información constructor:

notificationBuilder 
     ... 
     .setDeleteIntent(createDeleteIntent()) 
     ... 

Donde, createDeleteIntent es el siguiente método:

private PendingIntent createDeleteIntent() { 
    Intent intent = new Intent(); 
    intent.setAction(Config.NotificationDeleteAction); 

    return PendingIntent.getBroadcast(
      context, 
      0, 
      intent, 
      PendingIntent.FLAG_ONE_SHOT 
    ); 
} 

Su receptor de difusión registrado debe recibir el intento cuando su notificación sea descartada.

Cuestiones relacionadas