And. R.
And. R.

Reputation: 11

Clear app notifications in android studio

I have an application that sends notifications, but when the user leaves the application the notification is still there, in case he does not click on it. So, when the user logs out, or the session user is "null", the notifications will be automatically deleted.

My code:

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void enviarNotificacao(){
    Intent intent = new Intent(this, BottomNavigation.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    intent.putExtra("totens", listaTotem);

    int id = (int) (Math.random()*1000);
    PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setTicker("Olá Marujo!!!");
    builder.setContentTitle("Capitão Cupom");
    builder.setContentText("Um novo tesouro próximo de você");
    builder.setSmallIcon(R.drawable.logo);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo));
    builder.setContentIntent(pi);
    builder.setAutoCancel(true);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(id, builder.build());

    Notification n = builder.build();
    n.vibrate = new long[]{150, 300, 150, 600};
    notificationManager.notify(R.drawable.logo, n);

    try {
        Uri som  = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone toque = RingtoneManager.getRingtone(this, som);
        toque.play();
    }catch (Exception e){

    }
    Sessao.instance.setSailor(sailor);
}

Upvotes: 0

Views: 69

Answers (3)

Moklesur Rahman
Moklesur Rahman

Reputation: 791

When leaves the application call it

notificationManager.cancel(NOTIFICATION_ID);

Upvotes: 1

Dimness
Dimness

Reputation: 162

Override onPause() in Activity and put this inside:

NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);

Upvotes: 1

Gabe Sechan
Gabe Sechan

Reputation: 93728

NotificantionManager.cancel(id) cancels a notification with that id. NoticiationManager.cancelAll() cancels all notifications from this app. Detecting when a session ends will obviously be business logic you need to build. When it happens, call one of the 2 above functions.

Upvotes: 1

Related Questions