Search code examples
androidnotificationswindow

Is there a way to keep notification active until user clicks clear?


I have a service that runs in the background and notifies the user if they have a new PDF to view. When they click the notification a windows opens up giving them the option to download the PDF(s). The thing is that once the user closes this window they have no way to get back to that screen since the notification was cleared when they clicked it. I want this notification to remain active until the user clicks 'Clear Notifications' in the event they accidentally close the window the notification opens.*

*The reason I don't create a permanently accessible window/view in the app is because the notifications are time sensitive. After 20 minutes the PDFs are available for them to view at any time. Creating another permanent view would be redundant. This notification is only there to allow the user to view the PDFs a little earlier.

EDIT: following the answer provided by @Rahul Gupta, I figured out that my application was using 'FLAG_AUTO_CANCEL' if I did not specify a flag. So for my solution I just put in another flag. Since I'm using Titanium Appcelerator, I don't have a setAutoCancel() function so that wasn't an option for me.


Solution

  • For API below 11, you can set Notification.FLAG_NO_CLEAR. This can be implemented like this:

    // Create notification
    Notification note = new Notification(R.drawable.your_icon, "Example ", System.currentTimeMillis());
    
    // Set notification message
    note.setLatestEventInfo(context, "Some text", "Some more text", clickIntent);
    
    // THIS LINE IS THE IMPORTANT ONE            
    // This notification will not be cleared by swiping or by pressing "Clear all"
    note.flags |= Notification.FLAG_NO_CLEAR;
    

    For API levels above 11, or when using the Android Support Library, one can implement it like this:

    Notification noti = new Notification.Builder(mContext)
        .setContentTitle("title")
        .setContentText("content")
        .setSmallIcon(R.drawable.yourIcon)
        .setLargeIcon(R.drawable.yourBigIcon)
        .setOngoing(true) // Again, THIS is the important line. This method lets the notification to stay.
        .build();
    

    or you can use NotificationCompat class.

    public NotificationCompat.Builder setAutoCancel (boolean autoCancel)
    

    Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel. The PendingIntent set with setDeleteIntent(PendingIntent) will be broadcast when the notification is canceled.