Skip to content

Android: Make Your Notification Sticky

October 14th, 2014 - Software(1 min)

Following my quest from the previous article, I realised that my app would not be in the foreground, like an email, browser or a game might be, but it would work without any GUI, using something like a cron job. This is all nice and lovely, but I’m not fond of applications doing stuff behind my back.

I’ve seen in various applications that do something similar a pattern: there’s something on the screen telling me (the user) the application is running. That “something” is usually an icon on the status bar, coming from a notification. Moreover, that notification is always present.

Normal notifications disappear after you swipe them away (aka “OK, I’ve seen you”) or touch the notification (aka “Give me more details”). The notifications I’m thinking of are persistent; they don’t go away if clicked. They are “sticky”.

Android makes it easy to make sticky notifications; you just need to add Notification.FLAG_NO_CLEAR to the set of notification flags. I have found that you need also Notification.FLAG_ONGOING_EVENT. Otherwise the notification may disappear after a while.

The makeNotification() method from the previous post becomes:

private void makeNotification(Context context) {
    Intent intent = new Intent(context, MainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(context,
        NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder builder = new Notification.Builder(context)
        .setContentTitle("Notification Title")
        .setContentText("Sample Notification Content")
        .setContentIntent(pendingIntent)
        .setSmallIcon(R.drawable.ic_action_picture)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
        ;
    Notification n;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        n = builder.build();
    } else {
        n = builder.getNotification();
    }

    n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

    notificationManager.notify(NOTIFICATION_ID, n);
}

Simple.

HTH,

PS: Have a look at the previous post for the reference implementation!

Share on
Reddit
Linked in
Whatsapp

A little experiment: