Search code examples
androidandroid-layoutnotificationmanager

android -How to make notification disappear only when user clicked on it


this is my notification code:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    int icon = R.drawable.ic_launcher;
    CharSequence tickerText = "Ticker Text";
    long time = System.currentTimeMillis();

    Notification notification = new Notification(icon, tickerText, time);
    notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
    Context context = getApplicationContext();
    CharSequence contentTitle = "Title";
    CharSequence contentText = "Text";
    Intent notificationIntent = new Intent(this, FistActiivty.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    mNotificationManager.notify(1,notification);

How can I make the notification disappears only when user clicked on it , I mean I don't want the notification disappear when user clicks on clear button

thanks


Solution

  • Use:

    // This notification will not be cleared by swiping or by pressing "Clear all"
    notification.flags |= Notification.FLAG_NO_CLEAR;
    

    and also important:

    .setOngoing(true) //put this inside your notification builder
    

    or use: Notification.FLAG_ONGOING_EVENT; instead of .setOngoing(true)

    This should help you out.