How to increment push notification badge counter when app is in the background ?


#1

I am building an app with expo and when i send a notification to a target device i need to set the badge counter value but rather than specify a number in the payload it will be more accurate to increment the counter.

I know how to do it when the app is active using the getBadgeNumberAsync but what if the app is closed/inactive ?

This is my current payload. I send my notifications from my server (not from the client)

  body: {
         to:targetDevice,
         title:' you have a new notification',
         sound:"default",
         badge:1, // i need to find a way to increment the badge
         body:'Hello world', 
        }

Any advice about how i can handle this ?

Thanks


#2

handle on the server.
You dont need always to increase that number, sometimes you will resend the same notification…no?


#3

There’s no way to “increment” the number. The number you provide in the notification is what will be set on the badge. This is built-in to how push notifications operate on the OS in general I believe.

You’ll want to think about what the badge number is based on. Is it a number of unread messages? What constitutes “reading” a message? Because a user will not want that badge to stay there forever (and you need to tell your app when to clear it).

In our app, the badge number is based on unread messages. When a user receives a message, it starts with an unread flag set to true in our database. We send out a push notification with the badge number set to the total number of messages in the database for that user where unread is set to true.

When the user downloads the messages, the same API call that downloads the messages also flips the unread flag to false for all messages that are downloaded. At the same time the user downloads the messages in the app, the app also receives an updated count of the unread messages. Then we call setBadgeNumberAsync (https://docs.expo.io/versions/latest/sdk/notifications#exponotificationssetbadgenumberasyncnumber) with the updated number.


#4

Thanks you for your answer. Indeed, i understood that the only way to set the badge according to notification activities is to deal with the database to fetch some informations.

Now my problem is solved, i know how to handle this.

Thanks again.


closed #5

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.