[英]Android Create multiple notifications in recycler view
我正在創建一個應用程序,用於跟蹤食品何時過期,在適配器 class 中我有一個 if 語句,當項目到期日期小於 24 小時時,它會顯示通知,但是當我有多個項目即將到期時在我的回收站視圖中過期,它只顯示一個通知,我希望它在單獨的通知中顯示每個即將過期的項目。
if (timeLeft > 86400000) {
viewHolder.item_expire_date.setBackgroundColor(Color.parseColor("#3deb34"));
viewHolder.item_expire_date.setText(days + " Days \n" + hours + " Hours\n" + minutes + " Minutes\n" + seconds + " Seconds");
} else if (timeLeft > 0 && timeLeft <= 86400000) {
int reqCode = 1;
showNotification(context, items.getNAME()+ " Urgent expiry date", items.getNAME()+" is about to expire in less than 24 hours", reqCode);
viewHolder.item_expire_date.setBackgroundColor(Color.parseColor("#f55742"));
viewHolder.item_expire_date.setText(days + " Days \n" + hours + " Hours\n" + minutes + " Minutes\n" + seconds + " Seconds");
} else {
viewHolder.item_expire_date.setBackgroundColor(Color.parseColor("#000000"));
viewHolder.item_expire_date.setText("\"Re-enter Date\"");
}
創建通知
public void showNotification(Context context, String title, String message, int reqCode) {
String CHANNEL_ID = "channel_name";//
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Channel Name";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(reqCode, notificationBuilder.build());
}
您用於每個通知的reqCode
必須是唯一的。 一個簡單的解決方案是使用你的timeLeft
,假設每個食物都是獨一無二的。
這可以通過查看.notify
方法上方的注釋來驗證,特別是:
如果您的應用程序已經發布了具有相同 id 的通知並且尚未取消,它將被更新的信息替換。
源代碼:
/**
* Post a notification to be shown in the status bar. If a notification with
* the same id has already been posted by your application and has not yet been canceled, it
* will be replaced by the updated information.
*
* @param id An identifier for this notification unique within your
* application.
* @param notification A {@link Notification} object describing what to show the user. Must not
* be null.
*/
public void notify(int id, Notification notification)
{
notify(null, id, notification);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.