我正在处理一个项目,当我输入消息然后我将其作为通知发送给另一个用户使用广播它工作正常但当我再次发送新消息然后替换旧通知不创建新通知
下面是我生成通知的代码
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setColor(color)
.setSmallIcon(setNotificationIcon(mBuilder))
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Config.NOTIFICATION_ID, notification);
广播代码
public class IncomingReceiver extends BroadcastReceiver {
public static final String CUSTOM_INTENT = "jason.wei.custom.intent.action.TEST";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(CUSTOM_INTENT)) {
String message = intent.getStringExtra("message");
String chat_id = intent.getStringExtra("chat_id");
String username = intent.getStringExtra("username");
String chatType = intent.getStringExtra("chatType");
MyFirebaseMessagingService mMyFirebaseMessagingService = new MyFirebaseMessagingService();
Log.e("CHATID BROADCADST",chat_id);
Intent mIntent1;
if(chatType.equalsIgnoreCase("group")){
mIntent1=new Intent(context,ActivityChatMyGroup.class);
}else {
mIntent1=new Intent(context,ActivityChat.class);
}
Bundle mBundle=new Bundle();
mBundle.putString("name",username);
mIntent1.putExtras(mBundle);
mMyFirebaseMessagingService.showChatNotificationMessage(context, chat_id, username, message, mIntent1);
}
}
}
答案 0 :(得分:2)
每次显示通知时都应增加Config.NOTIFICATION_ID。如果两个通知具有相同的通知ID,则将替换先前的通知。
维护变量(静态或基于偏好等)并在方法中增加它
//偏好
int notificationId = PreferenceManager.getDefaultSharedPreferences(context).getInt("Notification_ID", 0);
notificationId++;
PreferenceManager.getDefaultSharedPreferences (context).edit().putInt("Notification_ID", notificationId).apply();
然后使用此变量
notificationManager.notify(notificationId, notification);