I am using expo for react-native application. I wanted to add a functionality where I could show notification when actual time will be the same as a hardcoded time in code. The problem is that it works when I have my app in expo opened but doesn't when it is in background. Here is the notifications handler that should run it in background:
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
Here is my useEffect for setting push notifications:
useEffect(() => {
registerForPushNotificationsAsync().then((token: any) => {
setExpoPushToken(token);
});
notificationListener.current = Notifications.addNotificationReceivedListener(
(notification: any) => {
setNotification(notification);
}
);
responseListener.current = Notifications.addNotificationResponseReceivedListener(
(response) => {
console.log(response);
}
);
return () => {
Notifications.removeNotificationSubscription(notificationListener);
Notifications.removeNotificationSubscription(responseListener);
};
}, []);
And here is the code for registering and sending notifications with token:
async function sendPushNotification() {
await Notifications.scheduleNotificationAsync({
content: {
title: "You've got mail! ",
body: "Here is the notification body",
data: { data: "goes here" },
},
trigger: { seconds: 1 },
});
}
async function registerForPushNotificationsAsync() {
let token;
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Permissions.askAsync(
Permissions.NOTIFICATIONS
);
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
}
else {
alert("Must use physical device for Push Notifications");
}
return token;
}
So I just use sendPushNotification() function for sending it. It works when I the app is open but after minimising it it doesn't show anything. How can I fix this?