如何在android中显示多个通知

如何在android中显示多个通知,android,notifications,android-notifications,Android,Notifications,Android Notifications,我只收到一个通知,如果有另一个通知,它将替换上一个通知,这是我的代码 private static void generateNotification(Context context, String message, String key) { int icon = R.drawable.ic_launcher; long when = System.currentTimeMillis(); NotificationManager notification

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

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

}

把你的线路换成这个

 notificationManager.notify(Unique_Integer_Number, notification);

希望它能对您有所帮助。

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


问题在于您的
通知ID
。将其视为数组索引。每次更新通知时,
notificationId
是存储值的位置。由于不增加int值(在本例中为
notificationId
),因此始终会替换上一个值。我想最好的解决方案是在更新通知之后增加它。如果您想保持它的持久性,那么您可以将
通知ID的值存储在
共享引用中。无论何时回来,您都可以抓取存储在
SharedReferences
中的最后一个整数值(
notificationId
)并使用它。

我这样解决了我的问题

/**
     * 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());
    }
/**
*发出通知,通知用户服务器已发送消息。
*/
私有静态void generateNotification(上下文上下文、字符串消息、,
字符串键、字符串msgId、字符串branchId){
int icon=R.drawable.ic_启动器;
长时间=System.currentTimeMillis();
通知建造商和建造商;
Uri alarmSound=铃声管理器
.getDefaultUri(RingtoneManager.TYPE_通知);

nBuilder=新通知compat.Builder(上下文) .setSmallIcon(R.drawable.ic_启动器) .setContentTitle(“智能共享-”+密钥) .setLights(Color.BLUE,500500).setContentText(消息) .setAutoCancel(true).setTicker(“来自smartshare的通知”) .setVibrate(新长[]{100250100250100250}) .设置声音(报警声音); 字符串consumerid=null; 整数位置=空; Intent resultent=null; if(consumerid!=null){ if(msgId!=null&&!msgId.equalsIgnoreCase(“”){ if(key!=null&&key.equalsIgnoreCase(“Yo!Matter”)){ ViewYoDataBase db_yo=新的ViewYoDataBase(上下文); position=db_yo.getPosition(msgId); 如果(位置!=null){ resultIntent=新意图(上下文, 活动类); resultent.putExtra(“id”,Integer.parseInt(msgId)); 结果:putExtra(“位置”,位置); 结果。putExtra(“notRefresh”、“notRefresh”); }否则{ resultIntent=新意图(上下文, 碎片(活动类); 结果:putExtra(键,键); } }else if(key!=null&&key.equalsIgnoreCase(“消息”)){ resultIntent=新意图(上下文, 碎片(活动类); 结果:putExtra(键,键); }. . . . . . }否则{ resultIntent=新意图(上下文、FragmentChangeActivity.class); 结果:putExtra(键,键); } }否则{ resultIntent=新意图(上下文,MainLoginSignUpActivity.class); } PendingEvent ResultPendingEvent=PendingEvent.getActivity(上下文, 通知(否、结果、挂起内容、标志更新(当前)); 如果(通知编号<9){ notify_no=notify_no+1; }否则{ 通知_no=0; } nBuilder.setContentIntent(resultPendingContent); NotificationManager nNotificationMgr=(NotificationManager)上下文 .getSystemService(上下文通知服务); notifymgr.notify(notify_no+2,nBuilder.build()); }
另一种方法是将当前日期转换为长日期,只需取最后4位数字。这个数字很可能是唯一的

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

以下是pass唯一通知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.
savedReferences
中的
notificationId
重置为特定范围,就像我在1000时那样。因此,它在未来不会产生任何问题。
如果您需要更多详细信息或任何查询,请告诉我。:)

使用共享首选项对我来说很有效

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

简单通知id需要可更改

只需为通知id创建随机数

    Random random = new Random();
    int m = random.nextInt(9999 - 1000) + 1000;
或者,您可以使用此方法创建tieorange告诉您的随机数(这将永远不会重复):

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

    notificationManager.notify(m, notification);

我想这会对某人有所帮助。
在下面的代码中,“not_nu”是一个随机整数。。PendingEvent和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;
}

uniqueIntNo
的位置放置如下唯一整数:

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

用这个替换你的线路

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

在代码中使用以下方法

方法调用:-

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;
    }
*返回唯一的通知id。
*/
公共静态整型getCurrentNotificationId(上下文iContext){
通知\u ID\u上限=30000;//任意数字。
通知ID下限=0;
SharedReferences SharedReferences=PreferenceManager.GetDefaultSharedReferences(iContext);
int-previousTokenId=SharedReferences.getInt(“currentNotificationTokenId”,0);
int currentTokenId=previousTokenId+1;
SharedReferences.Editor=SharedReferences.edit();
如果(currentTokenId是一个简单的c
  *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;
    }
private Integer notificationId = 0;

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

NotificationManager.notify(incrementNotificationId, notification);
declare class member
static int i = 0;

mNotificationManager.notify(++i, mBuilder.build());
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")
notificationManager.notify(0, notification);
new Random().nextInt() 
notificationManager.notify(new Random().nextInt(), notification);
 notificationManager.notify(Calendar.getInstance().timeInMillis.toInt(),notificationBuilder.build())