我正在编写一个每隔几秒通知一次的服务,一个通知出现一次,但预期的结果是它通知多次,它在列表中多次出现。
我知道通知 id 必须在多个通知之间更改才能出现多次,因此每次发送通知时我都使用 AtomicInteger 来增加通知 id。
在类的顶部,我声明了以下变量:
AtomicInteger count;
private Timer timer;
然后在 onCreate() 方法中,我有以下代码:
@Override
public void onCreate() {
count = new AtomicInteger(0);
final NotificationManager notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
Notification notification = new Notification.Builder(SiteCheckService.this)
.setContentTitle("Notification")
.setContentText("You should see this notification.")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build();
notificationManager.notify(count.incrementAndGet(), notification);
}
};
timer.schedule(task, 15000);
}
而onDestroy方法如下:
@Override
public void onDestroy() {
timer.cancel();
timer.purge();
}
我希望通知发送多次,但只发送一次。logcat 中没有错误。
海绵宝宝撒
拉风的咖菲猫
相关分类