Search code examples
javaandroidandroid-service

Notification only sent once from service


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.


Solution

  • 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);