我的通知代码突然停止工作

时间:2021-04-04 07:37:26

标签: java android notifications

我昨天收到了一条运行良好的通知,但没有出现该通知,而且我不记得我接触过代码.. 当我获得所需的值并且必须打开一个我们用户触摸它的弹出对话框时,必须出现该通知。

有人可以帮忙吗?

通知代码 - 在辅助服务中 - :

Intent notifyIntent = new Intent(context.getApplicationContext(), PopUp.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

//how I tried to pass data    
notifyIntent.putExtra("text1", text1);       
notifyIntent.putExtra("text2", text2);

PendingIntent pIntent = PendingIntent.getActivity(context, 1, notifyIntent, 0);

// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new NotificationCompat.Builder(context,CHANNEL_ID2)
.setContentTitle("check this")
.setSmallIcon(R.drawable.ic_delete)
.setContentIntent(pIntent)
.build();

NotificationManager notificationManager =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);

我使用的是 android studio 模拟器 API 30 在同一个服务类中,我有一个通知,它似乎表明该服务正在后台工作,除了通知我但它上面的代码突然没有工作

我不知道是什么问题,请帮忙

1 个答案:

答案 0 :(得分:1)

当使用notify 发出通知时,每个通知的notificationId 必须是唯一的int。更新您的代码以包含随机唯一的通知 ID

见下文

//you can use the timestamp
 int notificationId = Integer.parseInt(String.valueOf(System.currentTimeMillis()));

 NotificationManager notificationManager =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// notificationId is a unique int for each notification that you must define
  notificationManager.notify(notificationId, n);

Android Create a Notification