113

I am receiving only one notification and if there comes another notification, it replaces the previous one and here is my code

private static void generateNotification(Context context, String message,
        String key) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context,
            FragmentOpenActivity.class);
    notificationIntent.putExtra(key, key);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notification.defaults |= Notification.DEFAULT_SOUND;

    // notification.sound = Uri.parse("android.resource://" +
    // context.getPackageName() + "your_sound_file_name.mp3");
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);

}
Sonu Sourav
  • 2,926
  • 2
  • 12
  • 25
Kartheek Sarabu
  • 3,886
  • 8
  • 33
  • 66
  • 3
    As per official Document,you should not show multiple notifications from one app you have to stack all the notifications.. Have a look: http://developer.android.com/design/patterns/notifications_k.html – Gowtham Kumar Feb 26 '15 at 12:30

19 Answers19

149

just replace your line with this

 notificationManager.notify(Unique_Integer_Number, notification);

hope it will help you.

Sanket Shah
  • 4,352
  • 3
  • 21
  • 41
95

Simple notification_id needs to be changable.

Just create random number for notification_id.

    Random random = new Random();
    int m = random.nextInt(9999 - 1000) + 1000;

or you can use this method for creating random number as told by tieorange (this will never get repeated):

    int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);

and replace this line to add parameter for notification id as to generate random number

    notificationManager.notify(m, notification);
Hammad Nasir
  • 2,889
  • 7
  • 52
  • 133
sagar.android
  • 1,860
  • 17
  • 17
  • 11
    A bit hacky and runs into the possibility that you will end up with the same notification id, but this works if you need something really quick. – Muhammad Abdul-Rahim Nov 05 '15 at 16:24
  • 2
    If I see this right, the apporach from tieorange only works with seconds. So if you have multiple notifications at the same second, this will not work. – testing Sep 12 '17 at 16:01
  • 2
    @testing is right. thats why I have a 2nd step, m += random.nextInt(100) + 1; this might be one step extra but its way safer. I saw the above method fail in the last mins of an Auction/Bidding app. Hence i added another line for safety! – user3833732 Mar 13 '18 at 09:07
  • 1
    can also use current timestamp System.currentTimeMillis().toInt() – Nitin Feb 22 '22 at 18:49
28

Using Shared Preferences worked for me

SharedPreferences prefs = getSharedPreferences(Activity.class.getSimpleName(), Context.MODE_PRIVATE);
int notificationNumber = prefs.getInt("notificationNumber", 0);
...

notificationManager.notify(notificationNumber , notification);
SharedPreferences.Editor editor = prefs.edit();
notificationNumber++;
editor.putInt("notificationNumber", notificationNumber);
editor.commit();
vLopez
  • 445
  • 7
  • 15
13

Replace your line with this.

notificationManager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);
Tony Baby
  • 7,176
  • 6
  • 18
  • 22
9

i guess this will help someone..
in below code "not_nu" is an random int.. PendingIntent and Notification have the same ID .. so that on each notification click the intent will direct to different activity..

private void sendNotification(String message,String title,JSONObject extras) throws JSONException {
   String id = extras.getString("actionParam");
    Log.e("gcm","id  = "+id);
    Intent intent = new Intent(this, OrderDetailActivty.class);
    intent.putExtra("id", id);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    final int not_nu=generateRandom();
    PendingIntent pendingIntent = PendingIntent.getActivity(this, not_nu /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_cart_red)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(not_nu /* ID of notification */, notificationBuilder.build());
}
public int generateRandom(){
    Random random = new Random();
    return random.nextInt(9999 - 1000) + 1000;
}
Muneef M
  • 1,094
  • 15
  • 17
  • My notifications are not stacking still, is there any specific things I ahve to do besides what you show here? – Lion789 Oct 07 '16 at 07:05
  • What is that random.nextInt calculation doing there...can you explain??? 9999-1000???? what is that... – Radu Nov 30 '17 at 11:36
  • @Radu as you can see in the code "notificationManager.notify( " takes an int ( ID for notification ) as the first parameter. if this Int ( ID ) is same for new notification it will replace the old one and shows the new. if this Int(ID) is different then the new notification is treated separately and shows as stacks. so the older notification stays. and to achieve this. we are creating random int and assigning as ID. "random.nextInt(9999 - 1000) + 1000;" using this code. – Muneef M Dec 09 '17 at 16:18
  • @Lion789 you just have to use different ID for new notifications then it should stack up the notifications. – Muneef M Dec 09 '17 at 16:22
  • new NotificationCompat.Builder(this); is deprecated in Android Oreo, Please check docs and use Notification Channel implementation. – TapanHP Apr 26 '18 at 06:31
5

At the place of uniqueIntNo put unique integer number like this:

mNotificationManager.notify(uniqueIntNo, builder.build());
gvuksic
  • 2,983
  • 3
  • 32
  • 37
Sachin Singh
  • 149
  • 1
  • 7
5
notificationManager.notify(0, notification);

Put this code instead of 0

new Random().nextInt() 

Like below it works for me

notificationManager.notify(new Random().nextInt(), notification);
mehdi
  • 340
  • 4
  • 17
  • 1
    From Review: Hi, please don't answer just with source code. Try to provide a nice description about how your solution works. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Thanks – sɐunıɔןɐqɐp Jan 23 '19 at 11:38
4

You need to add a unique ID to each of the notifications so that they do not combine with each other. You can use this link for your reference :

https://github.com/sanathe06/AndroidGuide/tree/master/ExampleCompatNotificationBuilder

arshu
  • 11,805
  • 3
  • 23
  • 21
3

I solved my problem like this...

/**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message,
            String keys, String msgId, String branchId) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationCompat.Builder nBuilder;
        Uri alarmSound = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        nBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Smart Share - " + keys)
                .setLights(Color.BLUE, 500, 500).setContentText(message)
                .setAutoCancel(true).setTicker("Notification from smartshare")
                .setVibrate(new long[] { 100, 250, 100, 250, 100, 250 })
                .setSound(alarmSound);
        String consumerid = null;
        Integer position = null;
        Intent resultIntent = null;
        if (consumerid != null) {
            if (msgId != null && !msgId.equalsIgnoreCase("")) {
                if (key != null && key.equalsIgnoreCase("Yo! Matter")) {
                    ViewYoDataBase db_yo = new ViewYoDataBase(context);
                    position = db_yo.getPosition(msgId);
                    if (position != null) {
                        resultIntent = new Intent(context,
                                YoDetailActivity.class);
                        resultIntent.putExtra("id", Integer.parseInt(msgId));
                        resultIntent.putExtra("position", position);
                        resultIntent.putExtra("notRefresh", "notRefresh");
                    } else {
                        resultIntent = new Intent(context,
                                FragmentChangeActivity.class);
                        resultIntent.putExtra(key, key);
                    }
                } else if (key != null && key.equalsIgnoreCase("Message")) {
                    resultIntent = new Intent(context,
                            FragmentChangeActivity.class);
                    resultIntent.putExtra(key, key);
                }.
.
.
.
.
.
            } else {
                resultIntent = new Intent(context, FragmentChangeActivity.class);
                resultIntent.putExtra(key, key);
            }
        } else {
            resultIntent = new Intent(context, MainLoginSignUpActivity.class);
        }
        PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
                notify_no, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (notify_no < 9) {
            notify_no = notify_no + 1;
        } else {
            notify_no = 0;
        }
        nBuilder.setContentIntent(resultPendingIntent);
        NotificationManager nNotifyMgr = (NotificationManager) context
                .getSystemService(context.NOTIFICATION_SERVICE);
        nNotifyMgr.notify(notify_no + 2, nBuilder.build());
    }
Kartheek Sarabu
  • 3,886
  • 8
  • 33
  • 66
3

Another way of doing it is take the current date convert it into long just take the last 4 digits. There is a high probability that the number will be unique.

    long time = new Date().getTime();
    String tmpStr = String.valueOf(time);
    String last4Str = tmpStr.substring(tmpStr.length() -5);
    int notificationId = Integer.valueOf(last4Str);
Vidyadhara
  • 31
  • 1
3

You just need to change your one-line from notificationManager.notify(0, notification); to notificationManager.notify((int) System.currentTimeMillis(), notification);...

This will change the id of notification whenever the new notification will appear

Arun Sriramula
  • 124
  • 1
  • 13
0

The problem is with your notificationId. Think it as an array index. Each time you update your notification, the notificationId is the place it takes to store value. As you are not incrementing your int value (in this case, your notificationId), this always replaces the previous one. The best solution I guess is to increment it just after you update a notification. And if you want to keep it persistent, then you can store the value of your notificationId in sharedPreferences. Whenever you come back, you can just grab the last integer value (notificationId stored in sharedPreferences) and use it.

Muhammad Abdul-Rahim
  • 1,980
  • 19
  • 31
androCoder-BD
  • 498
  • 7
  • 13
0

Below is the code for pass unique notification id:

//"CommonUtilities.getValudeFromOreference" is the method created by me to get value from savedPreferences.
String notificationId = CommonUtilities.getValueFromPreference(context, Global.NOTIFICATION_ID, "0");
int notificationIdinInt = Integer.parseInt(notificationId);

notificationManager.notify(notificationIdinInt, notification);

// will increment notification id for uniqueness
notificationIdinInt = notificationIdinInt + 1;
CommonUtilities.saveValueToPreference(context, Global.NOTIFICATION_ID, notificationIdinInt + "");
//Above "CommonUtilities.saveValueToPreference" is the method created by me to save new value in savePreferences.

Reset notificationId in savedPreferences at specific range like I have did it at 1000. So it will not create any issues in future. Let me know if you need more detail information or any query. :)

mehdi
  • 340
  • 4
  • 17
Gaurav Darji
  • 488
  • 5
  • 12
  • hello can you post full code well we know to generate multiple notification need unique id but after generate we also have to cancel that particular notification .. there is problem to save and get each unique id in my case if you can help pls – Jayman Jani Jan 19 '17 at 06:38
0

Use the following method in your code.

Method call :-

notificationManager.notify(getCurrentNotificationId(getApplicationContext()), notification);

Method:-

  *Returns a unique notification id.
         */

        public static int getCurrentNotificationId(Context iContext){

            NOTIFICATION_ID_UPPER_LIMIT = 30000; // Arbitrary number.

            NOTIFICATION_ID_LOWER_LIMIT = 0;
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(iContext);
        int previousTokenId= sharedPreferences.getInt("currentNotificationTokenId", 0);

        int currentTokenId= previousTokenId+1;

        SharedPreferences.Editor editor= sharedPreferences.edit();

        if(currentTokenId<NOTIFICATION_ID_UPPER_LIMIT) {

            editor.putInt("currentNotificationTokenId", currentTokenId); // }
        }else{
            //If reaches the limit reset to lower limit..
            editor.putInt("currentNotificationTokenId", NOTIFICATION_ID_LOWER_LIMIT);
        }

        editor.commit();

        return currentTokenId;
    }
mehdi
  • 340
  • 4
  • 17
Sreekanth Karumanaghat
  • 3,383
  • 6
  • 44
  • 72
0

For Kotlin.

 notificationManager.notify(Calendar.getInstance().timeInMillis.toInt(),notificationBuilder.build())
Jayant Dhingra
  • 526
  • 6
  • 11
-1

A simple counter may solve your problem.

private Integer notificationId = 0;

private Integer incrementNotificationId() {
   return notificationId++;
}

NotificationManager.notify(incrementNotificationId, notification);
nirfrea
  • 84
  • 3
-1
declare class member
static int i = 0;

mNotificationManager.notify(++i, mBuilder.build());
juzraai
  • 5,693
  • 8
  • 33
  • 47
amar
  • 9
  • 2
-1
val notifyIdLong = ((Date().time / 1000L) % Integer.MAX_VALUE)
var notifyIdInteger = notifyIdLong.toInt()
if (notifyIdInteger < 0) notifyIdInteger = -1  * notifyIdInteger // if it's -ve change to positive
notificationManager.notify(notifyIdInteger, mBuilder.build())
log.d(TAG,"notifyId = $notifyIdInteger")
EdgeDev
  • 2,376
  • 2
  • 20
  • 37
-1
val notificationId = System.currentTimeMillis().toInt()
val i = Intent(applicationContext, HomeActivity::class.java)
val pendingIntent =
    PendingIntent.getActivity(this, notificationId, i, PendingIntent.FLAG_CANCEL_CURRENT)
//put notification id in pending intent and for notify manager.

mNotificationManager.notify(num, notificationnn)
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574