Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ANDROID & IOS: Press notification not have data on quit state and foreground but have data in background #1128

Open
phobo99 opened this issue Oct 21, 2024 · 3 comments
Labels
Keep Open this label avoids the stale bot

Comments

@phobo99
Copy link

phobo99 commented Oct 21, 2024

i have some problem about my notification no data while in app and when quit state. here is my code to handle notification, am i doing something wrong? please help me, below is the code:

useNotificationFCM:

import { storage } from "@/services/storage";
import { RootStackParamList } from "@/types/navigation";
import notifee, {
  AndroidImportance,
  EventDetail,
  EventType,
} from "@notifee/react-native";
import messaging, {
  FirebaseMessagingTypes,
} from "@react-native-firebase/messaging";
import { NavigationProp, useNavigation } from "@react-navigation/native";
import { useEffect } from "react";
import { PermissionsAndroid, Platform } from "react-native";

export const AndroidNotificationChannelId = "App";
export const AndroidNotificationChannelName = "App";

const useNotificationFCM = () => {
  const navigation = useNavigation<NavigationProp<RootStackParamList>>();
  // const authToken = useUserStore(store => store.authToken);
  async function onReceiveMessage(
    remoteMessage: FirebaseMessagingTypes.RemoteMessage | EventDetail
  ) {
    console.log("Received notification message: ", remoteMessage);
    await notifee.displayNotification({
      title: remoteMessage.notification?.title || "App",
      body: remoteMessage.notification?.body || "New notification",
      android: {
        channelId: AndroidNotificationChannelId,
        importance: AndroidImportance.HIGH,
        ongoing: true,
        smallIcon: "ic_stats_notification",
        color: "#000000",
      },
    });
  }

  const requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission();
    if (Platform.OS === "ios") {
      const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;
      return enabled;
    }

    await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
    );

    // Request permissions (required for iOS)
    await notifee.requestPermission();
    // Create a channel (required for Android)
    await notifee.createChannel({
      id: AndroidNotificationChannelId,
      name: AndroidNotificationChannelName,
      importance: AndroidImportance.HIGH,
    });
    return true;
  };

  async function registerFCMTokenOnAppStart() {
    if (Platform.OS === "android") {
      await messaging().registerDeviceForRemoteMessages();
    }
    try {
      const token = await messaging().getToken();
      console.log("registerFCMToken-->", token);
      if (token) storage.set("deviceToken", token);
    } catch (error) {
      console.log("registerFCMToken Device Token error ", error);
    }
  }

  async function onAppOpenedByNotification() {
    const initialNotification = await notifee.getInitialNotification();

    console.log("App opened by notification ", initialNotification);
    if (initialNotification) {
      console.log(
        "Notification caused application to open",
        initialNotification.notification
      );
    }
  }

  useEffect(() => {
    // if (authToken) {
    void registerFCMTokenOnAppStart();
  }, []);

  useEffect(() => {
    async function init() {
      console.log("Initializing FCM handler");
      await requestUserPermission();
      await onAppOpenedByNotification();
      // messaging().setBackgroundMessageHandler(onReceiveMessage);
      messaging().onNotificationOpenedApp(
        (remoteMessage: FirebaseMessagingTypes.RemoteMessage) => {
          console.log("Notification received OPEN APP", remoteMessage);
          // navigate in here
        }
      );
    }

    void init();
    const unsubscribe = messaging().onMessage(onReceiveMessage);

    return () => {
      unsubscribe();
    };
  }, []);

  useEffect(() => {
    const unsubscribe = notifee.onForegroundEvent(({ type, detail }) => {
      console.log("Notification received in foreground", type, detail);
      switch (type) {
        case EventType.DISMISSED:
          console.log("User dismissed notification", detail.notification);
          break;
        case EventType.PRESS:
          console.log("User pressed notification", detail.notification);
          // handle navigate in here
          break;
        case EventType.DELIVERED:
          console.log("Notification delivered", detail.notification);
          break;
        case EventType.FG_ALREADY_EXIST:
          console.log(
            "Notification already in foreground",
            detail.notification
          );
          break;
        case EventType.TRIGGER_NOTIFICATION_CREATED:
          console.log("Notification triggered");
          break;
        default:
          break;
      }
    });

    notifee.onBackgroundEvent(async ({ type, detail }) => {
      console.log("Notification received in background", type, detail);
      switch (type) {
        case EventType.ACTION_PRESS:
          console.log(
            "User pressed notification from background",
            type,
            detail
          );
          if (
            detail.notification?.data &&
            Object.keys(detail.notification?.data).length > 0
          ) {
            // handle navigate in here
          } else {
            navigation.navigate("Notifications");
          }
          break;
        case EventType.DISMISSED:
          console.log(
            "User dismissed notification from background",
            type,
            detail
          );
          break;
        case EventType.DELIVERED:
          console.log(
            "Notification delivered from background",
            detail.notification
          );
          break;
        case EventType.PRESS:
          console.log(
            "User pressed notification from background",
            type,
            detail
          );
          break;
        case EventType.FG_ALREADY_EXIST:
          console.log(
            "Notification already in foreground from background",
            detail.notification
          );
          break;
        case EventType.TRIGGER_NOTIFICATION_CREATED:
          console.log("Notification triggered from background");
          break;
        default:
          break;
      }
    });

    return () => {
      unsubscribe();
    };
  }, []);
};
export default useNotificationFCM;

`

NotificationHandler:

import useNotificationFCM from '@/utils/hooks/useNotificationFCM';

function NotificationHandler() {
  useNotificationFCM();

  return null;
}

export default NotificationHandler;

because I need to put in to be able to handle clicking on notifications to navigate them (inside

And I haven't done anything in index.js yet, thank you everyone for reading the article, I hope to get help.

@phobo99
Copy link
Author

phobo99 commented Oct 21, 2024

and idk i have double notification in android

Screenshot 2024-10-21 at 19 09 29

@LunatiqueCoder
Copy link

Possible duplicate. See:

Also this code snippet might be helpful (check firebase's payload, NOT notifee's!):

https://github.com/LunatiqueCoder/expo-notifee-plugin?tab=readme-ov-file#-usage

Copy link

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Dec 9, 2024
@mikehardy mikehardy reopened this Dec 9, 2024
@mikehardy mikehardy added Keep Open this label avoids the stale bot and removed Type: Stale labels Dec 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Keep Open this label avoids the stale bot
Projects
None yet
Development

No branches or pull requests

3 participants