Generate int unique id as android notification id

private static final String PREFERENCE_LAST_NOTIF_ID = "PREFERENCE_LAST_NOTIF_ID";

private static int getNextNotifId(Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    int id = sharedPreferences.getInt(PREFERENCE_LAST_NOTIF_ID, 0) + 1;
    if (id == Integer.MAX_VALUE) { id = 0; } // isn't this over kill ??? hahaha!!  ^_^
    sharedPreferences.edit().putInt(PREFERENCE_LAST_NOTIF_ID, id).apply();
    return id;
}

Maybe not the best, but definitely the simplest is to use current time.

int oneTimeID = (int) SystemClock.uptimeMillis();
mNotificationManager.notify(oneTimeID, mBuilder.build());

The good: this is the easiest way to get increasing ids.

The bad: time is a long and we're truncating it to half of that. This means that the counter will wrap around every 2'147'483'647 /1000(ms->s)/60(s->m)/60(m->h)/24(h->d) =~25 days.

SystemClock.uptimeMillis() has 2 advantages over currentTimeMillis:

  1. discounts all the milliseconds spent at deep sleep, what decreases amount of wraparounds.
  2. starts at 0 when the phone is restarted.

You are using the same notification ID (the value is always 1) for all your notifications. You probably should separate out the notification ID into a separate singleton class:

public class NotificationID {
    private final static AtomicInteger c = new AtomicInteger(0);
    public static int getID() {
        return c.incrementAndGet();
    }
}

Then use NotificationID.getID() instead of NOTIFICATION_ID in your code.

EDIT: As @racs points out in a comment, the above approach is not enough to ensure proper behavior if your app process happens to be killed. At a minimum, the initial value of the AtomicInteger should be initialized from some activity's saved state rather than starting at 0. If the notification IDs need to be unique across restarts of the app (again, where the app process may be killed off), then the latest value should be saved somewhere (probably to shared prefs) after every increment and restored when the app starts.


For anyone still looking around. I generated a timestamp and used it as the id.

import java.util.Date;
import java.util.Locale;

public int createID(){
   Date now = new Date();
   int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss",  Locale.US).format(now));
   return id;
}

Use it like so

int id = createID();
mNotifyManager.notify(id, mBuilder.build());