Generate int unique id as android notification id Generate int unique id as android notification id android android

Generate int unique id as android notification id


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());


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;}