Clear Previous Expo Push Notifications - react-native

I have my app in Expo pushing a notification when somebody sends a message, but if that person sends multiple messages a second notification is pushed.
Is there anything I can do to clear the previous notification, or simply update the notification instead of adding a second notification to the list?
Basically I need to force an override or dismiss previous notifications.
The approach I was hoping to use was to add a listener which cleared notifications before appending, but it seems that this only works when the app is in the foreground.
Is there a recommended approach to this currently?

You can clear any or all previous notifications in expo-notifications. Your question is not clear but I am guessing you want to clear all previous notification if new notification is received. You have to spot the best place when to clear notifications on your code. But here are some tips (use the following code in the useEffect hook) -
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
// DISMISS ALL NOTIFICATION AFTER INTERACTION
Notifications.dismissAllNotificationsAsync();
});
If you want to dismiss specific notification in that case, use dismissNotificationAsync(identifier: string): Promise method.
Just in case, if you want to dismiss all notifications when receiving a new one while the app is foregrounded (use the following code in the useEffect hook).
// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
// setNotification(notification);
// DISMISS ALL NOTIFICATION UPON RECEIVING NOTIFICATION WHILE IN FOREGROUND
Notifications.dismissAllNotificationsAsync();
});
You can use Notifications.dismissAllNotificationsAsync() method or dismissNotificationAsync(identifier: string): Promise method anywhere you like but you need to spot where to best use them.

_handleNotification = (notification) => {
this.setState({notification: notification});
console.log('get notification', this.state.notification);
let localnotificationId = this.state.notification.notificationId;
setTimeout(function () {
Notifications.dismissNotificationAsync(localnotificationId);
}, 10000)
};
This is how I do in NodeJS

Related

How to bring a react native(expo) app to the foreground when user recieves a notification

I have set up expo notification wherein my app listens to incoming notifications and can execute tasks in the background but my question is how do I bring the app to the foreground upon receiving a notification without the user pressing on the notification first?
Something like this:
import * as Notifications from "expo-notifications";
import * as TaskManager from "expo-task-manager";
const BACKGROUND_NOTIFICATION_TASK = "BACKGROUND-NOTIFICATION-TASK";
TaskManager.defineTask(
BACKGROUND_NOTIFICATION_TASK,
({ data, error, executionInfo }) => {
console.log("Received a notification in the background!");
// Bring the app to the foreground
}
);
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
The closest thing that you can do, is to create a local notification and encourage the user to press the notification to put the app to the foreground. But the exact thing you are asking is not possible with Android or either with iOS.

Duplicate fcm push notification in react native android backgroundhandler

I developed react native application with rnfirebase and notifee for sending the push notification. foreground is working properly, message is displayed only once. but the background notification is displaying twice like one is from messaging().setBackgroundMessageHandler and another one is android's default push notification. First message is from default push notification and next one is from firebase messaging. So how do I remove android's default push notification. I'm also checked that first default notification is not using the firebase messaging and notifee. It's comes from outside of react native like android's native push notification
The notifications that you are seeing are most likely one from firebase and another from Notifee.
In my project I was handling the notifications that were coming from firebase via firebase.messaging().onMessage and inside this listener I was showing a local notification using Notifee so that the notification shows in the foreground.
async showNotificationInForeground(message: FirebaseMessagingTypes.RemoteMessage) {
const { messageId, notification, data } = message
const channelId = await Notifee.createChannel({
id: messageId,
name: 'Pressable Channel',
importance: AndroidImportance.HIGH,
})
await Notifee.displayNotification({
title: notification?.title || '',
body: notification?.body || '',
data,
android: {
channelId,
importance: AndroidImportance.HIGH,
pressAction: {
id: messageId,
},
smallIcon: 'ic_stat_name',
localOnly: true,
},
})
}
However what was happening was that I was calling this showNotificationInForeground method to show the local Notifee notification on both firebase's background and messaging listeners ie: firebase.messaging().onMessage and firebase.messaging().setBackgroundMessageHandler
So what I ended up doing was only calling the showNotificationInForeground method in onMessage listener and not in setBackgroundMessageHandler, which resulted in showing the local notification in the foreground, and the firebase notification in the background.
If this is not the case for you, you are most likely registering an extra notification receiver inside your AndroidManifest.xml file which is causing the duplication
I had the same problem, where there were two notifications a) 1 from notifee (which I wanted to keep) b) from FCM (which I didnt want).
Sending a data only message from my custom server solved the issue. Below is a snippet of the serverside for sending data only message :
const admin = require("firebase-admin");
// Do other stuff like create an express server to listen and trigger sending message
// Note dont forget to to initialize the app
await admin.messaging().sendToDevice(
tokens, // ['token_1', 'token_2', ...]
{
data: {
owner: "Me",
user: "My Friend",
},
},
{
// Required for background/quit data-only messages on iOS
contentAvailable: true,
// Required for background/quit data-only messages on Android
priority: "high",
}
);
You can use other methods as well, just make sure that FCM doesnt include notification and is data only.

Notifications - Clear all notifications in the android notification tray

I'm sending multiple notifications to my app. What I want to achieve is whenever a user clicks one notification then all notifications in the notification tray disspear.
I've tried adding
notification.android.setAutoCancel(true)
which does the trick for only one notification (the one which is being clicked)
I've also tried:
firebase.notifications().removeAllDeliveredNotifications()
which doesn't have any effect.
How can I achieve this?
Here's my full code:
componentDidMount() {
firebase.notifications().removeAllDeliveredNotifications()
this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification) => {
});
this.notificationListener = firebase.notifications().onNotification(async (notification) => {
// Process your notification as required
notification.android.setAutoCancel(true)
firebase.notifications().removeAllDeliveredNotifications()
}
async componentWillMount() {
this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification) => {
});
this.notificationListener = firebase.notifications().onNotification((notification) => {
});
this.notificationDisplayedListener();
this.notificationListener();
}
Try moving the code for removing notifications
(removeAllDeliveredNotifications()) from onNotification listener to onNotificationOpened listener. There might be a race condition as you are trying to remove notifications on arrival.
Also because you want to clear notifications when user taps on one notification.
PS. Keep the notification listeners in either componentDidMount or componentWillMount, not both.

Alert is not displayed....When clicking on push notifications

I am running sample application..... I am using this module for push notifications..... My problem is when clicking on push notifications after clearing the instance of the app...In onNotification() console is printed but the alert is not displayed.... even try to keep time out for the alert but it doesn't work..... this is a problem is getting for the only iOS....... Please give any suggestions.......
onNotification: notification => {
console.log('NOTIFICATION:', notification)
if(notification.notificationType === XXX){
alert('NOTIFICATION:'+JSON.stringify(notification))
}
}

react native push notification that can be removed after button click

I am using react native v0.45.1.
How can I add to my application notification (no matter if the app is in the background or foreground) that the user can remove only after click an acknowledge button.
I don't want the user to swipe the notification aside without notice it.
how can it be done?
I am not sure https://github.com/wix/react-native-notifications will do what I need.
Edit
I want to have a notification that will act like:
'USB debugging connected
'Touch to disable USB debugging'
The notification can't be removed unless the user actively do something, in my case it will be 'click' on a button
after a lot of digging the solution I implemented was:
setting repeat interval for the notification.
for android:
repeatType: 'time',
repeatTime: timeSpan,
for iOS:
repeatType: 'minute',
when the user click the notification (decided its not the right approached to add actions - buttons - to notification):
PushNotification.configure({
onNotification: (notification) => {
console.log('NOTIFICATION:', notification);
const clicked = notification.userInteraction;
if (clicked) {
if (Platform.OS === 'ios') {
PushNotification.cancelLocalNotifications({ id: notification.data.id });
} else {
PushNotification.cancelLocalNotifications({ id: notification.id });
}
}
},
});
I am aware that this might not be the exact answer to this question. However,
I was looking for a similar solution earlier; how to remove notifications that hasn't been dismissed or opened by a user.
Sometimes the user might open the application / screen, without clicking on the notification. The notification will still be displayed in that case.
Using React Native with Expo, this is the solution I created for removing old notifications created using their Push Notification API.
import * as Notifications from "expo-notifications";
//...
// Remove notifications that exists for this conversation!
useEffect(() => {
Notifications.getPresentedNotificationsAsync().then(res => {
for (let k in res) {
if (
res[k].request.content.data &&
res[k].request.content.data.screen === "Conversations" &&
res[k].request.content.data.conversationId === conversationId
) {
Notifications.dismissNotificationAsync(res[k].request.identifier);
console.log("removed a notification for this conversation");
}
}
});
}, []);
By using the data sent to the Push Notification API, we can determine which notifications should be removed. in this case all notifications containing a conversationId matching the current value from the route are dismissed.