Expo Push Notifications only appearing in foreground, not background

The issue I am facing is related to sending push notifications using the Expo Push Notification API. I am sending HTTP POST requests to the Expo Push Notification V2 API to send notifications to Expo push token, which is obtained by registering the device with Expo. The problem is that the notifications are only appearing in the foreground and not in the background. However, when I test sending notifications using Postman and expo push notification tool, they appear in the the background.

I have checked that the necessary permissions and code are in place to handle notifications in the background, and that the device settings are allowing notifications in the background. I have also double-checked my implementation of the Expo push notifications API in my app to ensure that I am sending the correct data to the Expo server and that I am handling the response correctly. Additionally, i turned off battery saver and also tried on other phones but all in vain, i also built an standalone apk but same issue with that one also.

I have followed this guide https://docs.expo.dev/push-notifications/push-notifications-setup/

I am seeking help to understand why the notifications are not appearing in the background when sent from my Expo app, but are appearing when I test them using Postman and expo push notification tool. I would appreciate any guidance or suggestions on how to troubleshoot this issue.

Here’s my App.js code:

async function registerForPushNotificationsAsync() {
	let token;
	if (Device.isDevice) {
		const { status: existingStatus } =
			await Notifications.getPermissionsAsync();
		let finalStatus = existingStatus;
		if (existingStatus !== "granted") {
			const { status } = await Notifications.requestPermissionsAsync();
			finalStatus = status;
		}
		if (finalStatus !== "granted") {
			alert("Failed to get push token for push notification!");
			return;
		}
		token = (await Notifications.getExpoPushTokenAsync()).data;
	} else {
		alert("Must use physical device for Push Notifications");
	}

	if (Platform.OS === "android") {
		Notifications.setNotificationChannelAsync("default", {
			name: "default",
			importance: Notifications.AndroidImportance.MAX,
			vibrationPattern: [0, 250, 250, 250],
			lightColor: "#FF231F7C",
		});
	}

	return token;
}

async function sendPushNotification(
	expoPushToken: any,
	type?: string,
	name?: string
) {

	const message = {
		to: expoPushToken,
		sound: "default",
		title: "HI",
		body: "BY",
	};

	await fetch("https://exp.host/--/api/v2/push/send", {
		method: "POST",
		headers: {
			Accept: "application/json",
			"Accept-encoding": "gzip, deflate",
			"Content-Type": "application/json",
		},
		body: JSON.stringify(message),
	});
}

export default function App() {
	const { isLoadingComplete, user, error, refresh } = useCachedResources();
	const [notifications, setNotifications] = useState<Notification[]>([]);
	const [expoPushToken, setExpoPushToken] = useState<any>();
	const [notification, setNotification] = useState<any>(false);
	const notificationListener = useRef<any>();
	const responseListener = useRef<any>();

	useEffect(() => {
		registerForPushNotificationsAsync().then((token) =>
			setExpoPushToken(token)
		);
		console.log("eee", expoPushToken);
		notificationListener.current =
			Notifications.addNotificationReceivedListener((notification) => {
				setNotification(notification);
			});

		responseListener.current =
			Notifications.addNotificationResponseReceivedListener(
				async (response) => {
					await Notifications.setBadgeCountAsync(0);
					navRef.navigate("Dashboard", {
						screen: "Messages",
					});
				}
			);

		return () => {
			Notifications.removeNotificationSubscription(
				notificationListener.current
			);
			Notifications.removeNotificationSubscription(responseListener.current);
		};
	}, []);

	useEffect(() => {
		const newNotifications = notifications?.filter(
			(not) => not.status === "new"
		);

		newNotifications?.forEach(async (not) => {
			await sendPushNotification(expoPushToken, not.type, not.by.name);
			updateNotification(not.id!!, {
				status: "old",
			});
		});
	}, [notifications]);

	useEffect(() => {
		// getFCMToken();
		let unsubscribeNotification: Unsubscribe;
		if (user && user.id) {
			unsubscribeNotification = subscribeNotification(
				user.id,
				handleNotificationChange
			);
		}
		return () => {
			if (unsubscribeNotification) {
				unsubscribeNotification();
			}
		};
	}, [user]);

	const handleNotificationChange = (snapshot: QuerySnapshot<Notification>) => {
		let result: Notification[] = [];
		snapshot.forEach((doc) => {
			result.push({ ...doc.data(), id: doc.id });
		});

		setNotifications(result);
	};

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