Reputation: 341
I am writing a service to notify every few seconds, and a notification appears once but the expected result is that it notifies multiple times, where it appears multiple times in the list.
I know that the notification id must change between multiple notifications for it to appear multiple times, so I used an AtomicInteger to increment the notification id every time the notification is sent.
At the top of the class I have the following variables declared:
AtomicInteger count;
private Timer timer;
Then in the method onCreate() I have the following code:
@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);
}
And the onDestroy method is as follows:
@Override
public void onDestroy() {
timer.cancel();
timer.purge();
}
I expect the notification to be sent multiple times, but it is only sent one time. There are no errors in logcat.
Upvotes: 0
Views: 153
Reputation: 341
I used the suggestions from ismail alaoui's answer to make sure the notification id is saved and I also changed the call to schedule to three parameters as follows so the TimerTask is called multiple times.
timer.schedule(task, 0, 15000);
Upvotes: 0
Reputation: 6073
i suggest you to use and store your notification in a sharedPreferences
element
final String Pref_Name = "Notification";
notificationPreferences = context.getSharedPreferences(Pref_Name, Context.MODE_PRIVATE);
editor = notificationPreferences.edit();
notificationCount = notificationPreferences.getInt("notifCountNumber", 0);
and after your notify()
method
editor.putInt("notifCountNumber",notificationCount+1);
editor.commit();
Upvotes: 1