Search code examples
androidnotificationsasync-onprogressupdate

displaying notification only once from onprogressupdate method


I am trying to display a notification only once from an onprogress update method. There is condition which will allow the notification to be displayed. The problem is that it continues to display notifications after the first one and the phone keeps on ringing and vibrating. I want to receive only one notification informing about something and stop. Is is possible? can someone help please and suggest alternative ways of doing it. Thanks.

Here's my code for the onPorgressUpdate method:

 protected void onProgressUpdate(byte[]... values) {
         super.onProgressUpdate(values);
         String command=new String(values[0]);//get the String from the recieved bytes
         String[] parts= command.split(",");
         String part1=parts[0];
         String part2=parts[1];

         temp.setText(part1);
         humi.setText(part2);

         if(Integer.parseInt(part2)>70)
         {
            NotificationCompat.Builder builder=new NotificationCompat.Builder(this.context);
            builder.setContentTitle("AM Home Automation");
            builder.setContentText("humi");
            builder.setSmallIcon(R.drawable.ic_launcher);
            builder.setTicker("alert");
            builder.setDefaults(Notification.DEFAULT_ALL);

            notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, builder.build());
         }

Solution

  • Use a boolean to remember you already showed the notification and use it to not show another one like below:

    private boolean alreadyDisplayedNotification = false;
    
    protected void onProgressUpdate(byte[]... values) {
        super.onProgressUpdate(values);
        String command=new String(values[0]);//get the String from the recieved bytes
        String[] parts= command.split(",");
        String part1=parts[0];
        String part2=parts[1];
    
        temp.setText(part1);
        humi.setText(part2);
    
        if(Integer.parseInt(part2)>70 && !alreadyDisplayedNotification) {
            NotificationCompat.Builder builder=new NotificationCompat.Builder(this.context);
            builder.setContentTitle("AM Home Automation");
            builder.setContentText("humi");
            builder.setSmallIcon(R.drawable.ic_launcher);
            builder.setTicker("alert");
            builder.setDefaults(Notification.DEFAULT_ALL);
    
            notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, builder.build());
    
            alreadyDisplayedNotification=true;
        }