首页 > 解决方案 > 我的通知代码突然停止工作

问题描述

我昨天有一个工作正常的通知,通知没有出现,我不记得我触摸过代码。当我获得所需的值时必须出现该通知,并且必须打开一个我们用户触摸它的弹出对话框。

有人可以帮忙吗?

通知代码-在服务中-:

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 emulator API 30 我有一个通知,它似乎表明该服务正在后台工作,除了我的通知,但它上面的代码突然没有工作

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

标签: javaandroidnotifications

解决方案


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

见下文

//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 创建通知


推荐阅读