[android] How to display multiple notifications in android

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

}

This question is related to android notifications android-notifications

The answer is


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.


just replace your line with this

 notificationManager.notify(Unique_Integer_Number, notification);

hope it will help you.


A simple counter may solve your problem.

private Integer notificationId = 0;

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

NotificationManager.notify(incrementNotificationId, notification);

Replace your line with this.

notificationManager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);

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. :)


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

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

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")

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

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

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

mNotificationManager.notify(uniqueIntNo, builder.build());

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

declare class member
static int i = 0;

mNotificationManager.notify(++i, mBuilder.build());

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


For Kotlin.

 notificationManager.notify(Calendar.getInstance().timeInMillis.toInt(),notificationBuilder.build())

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

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


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to notifications

NotificationCompat.Builder deprecated in Android O No notification sound when sending notification from firebase in android Android Push Notifications: Icon not displaying in notification, white square shown instead How to display multiple notifications in android Actionbar notification count icon (badge) like Google has How to display count of notifications in app launcher icon Android notification is not showing How to create a notification with NotificationCompat.Builder? Open application after clicking on Notification How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

Examples related to android-notifications

startForeground fail after upgrade to Android 8.1 NotificationCompat.Builder deprecated in Android O Notification not showing in Oreo Firebase FCM notifications click_action payload Notification bar icon turns white in Android 5 Lollipop INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE Android: Test Push Notification online (Google Cloud Messaging) How to display multiple notifications in android Android Notification Sound How to create a notification with NotificationCompat.Builder?