簡體   English   中英

Android:創建新通知后,舊通知被替換

[英]Android: After creating a new notification, the older one is replaced

我想在不取消/刪除我的應用程序中以前的通知的情況下創建通知。 這是我創建通知的代碼:

private void notification(Context context, String title, String content) {
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle(title)
            .setContentText(content);

    Intent resultIntent = new Intent(context, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    //Id allows you to update the notification later on.
    mNotificationManager.notify(100, mBuilder.build());
}

您正在為通知使用硬編碼 id,當然它會替換舊的。 嘗試使用可變 ID 而不是硬編碼的 100。

mNotificationManager.notify(100+x, mBuilder.build());

或類似的東西。

使用變量ID的通知,我都面臨着這個問題1小時前使用這種技術來解決這個問題。

        val id= Random(System.currentTimeMillis()).nextInt(1000)
        mNotificationManager?.notify(id, mBuilder.build())

對於長期解決方案,您可以使用隨機方法為您生成整數變量並在通知中調用它。

mNotificationManager.notify(createRandomCode(7), mBuilder.build());

public int createRandomCode(int codeLength) {
        char[] chars = "1234567890".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new SecureRandom();
        for (int i = 0; i < codeLength; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        return Integer.parseInt(sb.toString());
    }

在創建 PendingIntent 對象時,我們調用 PendingIntent.getActivity(mContext, requestCode , intent, PendingIntent.FLAG_UPDATE_CURRENT);

所以這里使用下面的代碼來生成 PendingIntent

Random objRandom = new Random();
    final PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mContext,
                    objRandom.nextInt(100),
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM