Updating an ongoing notification quietly

howettl picture howettl · Jun 20, 2011 · Viewed 54k times · Source

I have a service which connects to other devices wirelessly. When the service is enabled, I have an ongoing notification which states it is enabled.

After the service is enabled, the user then connects to another device. At this point, I would like to update my ongoing notification to state the name of the device which has been connected to. This is easy enough to do by calling startForeground(ONGOING_NOTIFICATION, notification) again with the updated information; however this flashes the notification on the bar each time it is called. What I would really like is the notification to quietly update in the background without flashing on the notification bar so the user doesn't know the difference until he or she opens the notification area to look.

Is there someway to update the notification without calling startForeground()?

This behavior only occurs in Honeycomb. Gingerbread devices (and I assume Froyo, etc.) behave the desired way.

Answer

Chris Noldus picture Chris Noldus · Mar 21, 2013

I too experienced this issue, and with help of previous comments and a bit of digging I have found the solution.

If you do not want notifications to flash when updated, or to continuously hog the status bar of the device,you must:

  • Use setOnlyAlertOnce(true) on the builder
  • Use the SAME Builder for each update.

If you use a new builder each time, then I am guessing Android has to rebuild the view all over again causing it to briefly disappear.

An example of some good code:

class NotificationExample extends Activity {

  private NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
  private mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  //Different Id's will show up as different notifications
  private int mNotificationId = 1;    

  //Some things we only have to set the first time.
  private boolean firstTime = true;

  private updateNotification(String message, int progress) {
    if (firstTime) {
      mBuilder.setSmallIcon(R.drawable.icon)
      .setContentTitle("My Notification")
      .setOnlyAlertOnce(true);
      firstTime = false;
    }
    mBuilder.setContentText(message)
    .setProgress(100, progress, true);

    mNotificationManager.notify(mNotificationId, mBuilder.build());
  }
}

With the above code, you can just call updateNotification(String, int) with a message and progress (0-100) and it will update the notification without annoying the user.