110

我只收到一个通知,如果有另一个通知,它会替换前一个通知,这是我的代码

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

}
4

19 回答 19

145

只需用这个替换你的行

 notificationManager.notify(Unique_Integer_Number, notification);

希望它会帮助你。

于 2013-08-07T11:23:39.277 回答
95

简单的 notification_id 需要是可变的。

只需为 notification_id 创建随机数。

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

或者您可以使用此方法创建由 tieorange 告知的随机数(这将永远不会重复):

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

并替换此行以添加通知 id 的参数以生成随机数

    notificationManager.notify(m, notification);
于 2014-11-04T10:36:50.720 回答
28

使用共享首选项对我有用

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();
于 2014-10-20T12:03:14.757 回答
13

用这个替换你的行。

notificationManager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);
于 2017-01-07T02:52:35.640 回答
9

我想这会对某人有所帮助..
在下面的代码中“not_nu”是一个随机整数.. PendingIntent 和 Notification 具有相同的 ID .. 所以在每个通知上单击意图将指向不同的活动..

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;
}
于 2015-09-27T15:42:00.907 回答
5

uniqueIntNo放置唯一整数的地方,如下所示:

mNotificationManager.notify(uniqueIntNo, builder.build());
于 2016-05-20T12:10:25.943 回答
5
notificationManager.notify(0, notification);

把这个代码而不是 0

new Random().nextInt() 

就像下面它对我有用

notificationManager.notify(new Random().nextInt(), notification);
于 2019-01-23T11:33:42.540 回答
4

您需要为每个通知添加一个唯一 ID,以便它们不会相互组合。您可以使用此链接作为参考:

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

于 2013-08-07T13:09:23.567 回答
3

我这样解决了我的问题...

/**
     * 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());
    }
于 2014-01-18T05:39:39.407 回答
3

另一种方法是将当前日期转换为 long,只需使用最后 4 位数字即可。该数字很可能是唯一的。

    long time = new Date().getTime();
    String tmpStr = String.valueOf(time);
    String last4Str = tmpStr.substring(tmpStr.length() -5);
    int notificationId = Integer.valueOf(last4Str);
于 2014-09-08T10:35:35.070 回答
3

您只需要将您的单行从更改notificationManager.notify(0, notification);notificationManager.notify((int) System.currentTimeMillis(), notification);...

每当出现新通知时,这将更改通知的 ID

于 2019-07-24T12:03:29.807 回答
0

问题出在你的notificationId. 将其视为数组索引。每次您更新通知时,notificationId它都是存储价值的地方。由于您没有增加您的 int 值(在本例中为您的notificationId),因此它始终会替换前一个值。我猜最好的解决方案是在更新通知后立即增加它。如果你想保持它的持久性,那么你可以存储你notificationIdin的值sharedPreferences。每当您回来时,您都可以获取最后一个整数值(notificationId存储在 中sharedPreferences)并使用它。

于 2014-01-04T20:28:13.303 回答
0

下面是传递唯一通知 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.

notificationId在特定范围内重置,savedPreferences就像我在 1000 处所做的那样。所以它不会在未来产生任何问题。如果您需要更多详细信息或任何查询,请告诉我。:)

于 2014-09-18T05:02:31.347 回答
0

在您的代码中使用以下方法。

方法调用:-

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

方法:-

  *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;
    }
于 2017-08-22T09:24:41.227 回答
0

对于科特林。

 notificationManager.notify(Calendar.getInstance().timeInMillis.toInt(),notificationBuilder.build())
于 2020-10-10T10:05:46.973 回答
0

val notificationId = System.currentTimeMillis().toInt()

val i = Intent(applicationContext, HomeActivity::class.java)

val pendingIntent = PendingIntent.getActivity(this, notificationId, i, PendingIntent.FLAG_CANCEL_CURRENT)

// 将通知 id 放在待处理的意图中并用于通知管理器。

mNotificationManager.notify(num, notificationnn)

于 2021-10-25T14:30:09.443 回答
-1

一个简单的计数器可能会解决您的问题。

private Integer notificationId = 0;

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

NotificationManager.notify(incrementNotificationId, notification);
于 2017-12-20T09:53:02.960 回答
-1
declare class member
static int i = 0;

mNotificationManager.notify(++i, mBuilder.build());
于 2018-07-14T08:20:38.090 回答
-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")
于 2018-09-26T13:56:40.297 回答