java - 通知仅显示一次,此后不再显示
问题描述
我有一个预定的 FirebaseJob,一旦完成,它会再次安排自己,下一个窗口 ON_ANY_NETWORK。它的工作做得很好,正如预期的那样。我从中调用一项服务,该服务每次都会以未决的意图创建一个新通知。喜欢 :
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra("NotificationMessage", "NotificationMessage");
//resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("My App name")
.setContentText("Content text")
.setTicker("This is a ticker text")
.setStyle(new NotificationCompat.BigTextStyle().bigText("This is a long text"))
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(resultPendingIntent)
.setAutoCancel(false)
.setOngoing(true)
.setColor(getResources().getColor(android.R.color.holo_red_dark));
if (notificationManager != null)
{
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
正如我所料,它仅第一次显示通知。我不希望任何用户滑动它,直到应用程序再次打开。一旦从此通知打开应用程序,我将取消通知,例如:
int MY_NOTIFICATION_ID= 234;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(MY_NOTIFICATION_ID);
但是,当我的作业再次开始执行并执行上面显示的用于创建通知的相同代码时,它会执行代码,但通知不会再次显示。董事会成员将不胜感激任何帮助。提前致谢。
解决方案
这是因为你MY_NOTIFICATION_ID
的总是一样的。相反,例如,您可以设置MY_NOTIFICATION_ID
为等于System.currentTimeMillis()
:
int MY_NOTIFICATION_ID= System.currentTimeMillis();
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(MY_NOTIFICATION_ID);
推荐阅读
- sql - 实时更新的仪表板,如何构建
- c# - AvalonEdit 如何在转换器中添加新语法
- java - Apache POI SAX XSSFReader 读取错误的日期格式
- apache - 有没有办法在 Apache HTTP Server 中实现 HTTP/3 (QUIC)?
- html - 部分标签中的列彼此堆叠而不是彼此相邻
- memory-leaks - BottomSheetDialogFragment 在 LeakCanary 2 中显示内存泄漏,但我不确定为什么?
- jenkins - 詹金斯插件
- ruby-on-rails - 需要在 factory 中指定 id 以进行关联
- postgresql - Postgresql SQL 抛出不明确的列错误
- sql-server - 将记录插入 SQL Server 数据库后刷新 datagridview