2013-02-03 11 views
66

Sto usando una notifica di Android per avvisare l'utente una volta che un servizio è finito (successo o fallimento), e voglio cancellare i file locali una volta che il processo è finito.catch on swipe per eliminare l'evento

Il mio problema è che in caso di errore - Voglio lasciare all'utente l'opzione "riprova". e se sceglie di non riprovare e di ignorare la notifica, voglio cancellare i file locali salvati per gli scopi del processo (immagini ...).

C'è un modo per rilevare l'evento swipe-to-dismiss della notifica?

risposta

104

DeleteIntent: DeleteIntent è un oggetto PendingIntent che può essere associato con una notifica e viene licenziato quando la notifica viene eliminato, l'etere da: azione specifica

  • utente
  • utente Eliminare tutte le notifiche .

È possibile impostare l'In attesa in sospeso su un destinatario di trasmissione e quindi eseguire qualsiasi azione desiderata.

Intent intent = new Intent(this, MyBroadcastReceiver.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0); 
    Builder builder = new Notification.Builder(this): 
..... code for your notification 
    builder.setDeleteIntent(pendingIntent); 

MyBroadcastReceiver

public class MyBroadcastReceiver extends BroadcastReceiver { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      .... code to handle cancel 
     } 

    } 
+0

Funziona :) grazie molto! –

+5

Questo è tardi. Mi stavo chiedendo se esiste un approccio simile per le notifiche che aveva 'builder.setAutoCancel (true);' perché quando un utente fa clic sulla notifica e viene cancellato, delete-Intent non viene attivato –

+1

@dev_android checkout http://developer.android.com/reference/android/app/Notification.Builder.html#setContentIntent(android.app.PendingIntent) –

66

Un completamente lavata risposta (con grazie a Mr. Me per la risposta):

1) Creare un ricevitore per gestire il colpo-to respingere l'evento:

public class NotificationDismissedReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     int notificationId = intent.getExtras().getInt("com.my.app.notificationId"); 
     /* Your code to handle the event here */ 
    } 
} 

2) Aggiungere una voce a voi r manifesta:

<receiver 
    android:name="com.my.app.receiver.NotificationDismissedReceiver" 
    android:exported="false" > 
</receiver> 

3) Creare l'intento attesa utilizzando un ID univoco per l'intento attesa (l'id di notifica viene utilizzato qui) come senza questo gli stessi extra saranno riutilizzati per ogni evento il licenziamento:

private PendingIntent createOnDismissedIntent(Context context, int notificationId) { 
    Intent intent = new Intent(context, NotificationDismissedReceiver.class); 
    intent.putExtra("com.my.app.notificationId", notificationId); 

    PendingIntent pendingIntent = 
      PendingIntent.getBroadcast(context.getApplicationContext(), 
             notificationId, intent, 0); 
    return pendingIntent; 
} 

4) Costruisci la tua notifica:

Notification notification = new NotificationCompat.Builder(context) 
       .setContentTitle("My App") 
       .setContentText("hello world") 
       .setWhen(notificationTime) 
       .setDeleteIntent(createOnDismissedIntent(context, notificationId)) 
       .build(); 

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
notificationManager.notify(notificationId, notification); 
+0

Ben fatto amico! –

+0

Non ha funzionato per me, è sempre risultato con errore "Impossibile istanziare il ricevitore .... non ha un costruttore di argomenti zero". Risolto solo dopo aver implementato un'altra soluzione simile ma con la registrazione del destinatario della trasmissione: http://stackoverflow.com/questions/13028122/how-to-use-delete-intent-to-perform-some-action-on -clear-notification –

+0

Questo funziona per me.Ma l'evento non può essere richiamato quando si fa clic sulla notifica. Come posso ascoltare l'evento click? –

0

Un'altra idea:

i Se crei una notifica normalmente hai bisogno anche delle azioni 1, 2 o 3. Ho creato un "NotifyManager", crea tutte le notifiche di cui ho bisogno e anche ricevere tutte le chiamate Intent. Così posso gestire tutte le azioni E anche il prendere l'evento di allontanamento in UN posto.

public class NotifyPerformService extends IntentService { 

@Inject NotificationManager notificationManager; 

public NotifyPerformService() { 
    super("NotifyService"); 
    ...//some Dagger stuff 
} 

@Override 
public void onHandleIntent(Intent intent) { 
    notificationManager.performNotifyCall(intent); 
} 

per creare il deleteIntent utilizzare questo (nel NotificationManager):

private PendingIntent createOnDismissedIntent(Context context) { 
    Intent   intent   = new Intent(context, NotifyPerformMailService.class).setAction("ACTION_NOTIFY_DELETED"); 
    PendingIntent pendingIntent = PendingIntent.getService(context, SOME_NOTIFY_DELETED_ID, intent, 0); 

    return pendingIntent; 
} 

e che uso per impostare l'intento di eliminazione come questo (nel NotificationManager):

private NotificationCompat.Builder setNotificationStandardValues(Context context, long when){ 
    String       subText = "some string"; 
    NotificationCompat.Builder  builder = new NotificationCompat.Builder(context.getApplicationContext()); 


    builder 
      .setLights(ContextUtils.getResourceColor(R.color.primary) , 1800, 3500) //Set the argb value that you would like the LED on the device to blink, as well as the rate 
      .setAutoCancel(true)             //Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel. 
      .setWhen(when)               //Set the time that the event occurred. Notifications in the panel are sorted by this time. 
      .setVibrate(new long[]{1000, 1000})          //Set the vibration pattern to use. 

      .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)) 
      .setSmallIcon(R.drawable.ic_white_24dp) 
      .setGroup(NOTIFY_GROUP) 
      .setContentInfo(subText) 
      .setDeleteIntent(createOnDismissedIntent(context)) 
    ; 

    return builder; 
} 

e infine nello stesso NotificationManager è la funzione di esecuzione:

public void performNotifyCall(Intent intent) { 
    String action = intent.getAction(); 
    boolean success = false; 

    if(action.equals(ACTION_DELETE)) { 
     success = delete(...); 
    } 

    if(action.equals(ACTION_SHOW)) { 
     success = showDetails(...); 
    } 

    if(action.equals("ACTION_NOTIFY_DELETED")) { 
     success = true; 
    } 


    if(success == false){ 
     return; 
    } 

    //some cleaning stuff 
} 
Problemi correlati