首页 > 解决方案 > 使用 Firebase 消息和 React Navigation(React Native,Android)在打开通知时导航到特定屏幕

问题描述

我有一个反应原生应用程序,它使用带有 firebase 消息传递和反应导航的远程通知。一切都很好,除了一段时间(或偶尔)通知侦听器不起作用。在我遇到任何问题之前可能需要长达 2 周的时间。这通常发生在应用程序已启动很长时间但未使用时,然后打开通知时,onNotificationOpenedApp不运行,即我只看到索引屏幕。我正在使用“react-native-bootsplash”,如果这可能与它有关吗?

此外,有时一个旧的通知会触发一个监听器,我假设它getInitialNotification被调用了两次(或多次)。android是否会半关闭一段时间未使用的应用程序,然后在应用程序再次打开时破坏侦听器?似乎该应用程序已部分卸载,然后出现问题。一旦问题发生,它很有可能会继续发生,直到我重新启动应用程序。

下面是注册监听器的代码:

getInitialNotification 当用户通过通知打开应用程序时,这将运行并返回通知。这是在getInitialUrl传递给NavigationContainer(react-navigation 组件)的道具中完成的,这是在他们的文档中推荐

<NavigationContainer
  ref={setNavigationRef}
  linking={{
    config: {
      initialRouteName: 'SignedIn',
    },
    getInitialURL: async () => {
      try {
        // If app was opened with deeplink
        const url = await Linking.getInitialURL();
        if (url !== null) return url;

        const notification = await messaging().getInitialNotification();

        if (notification !== null) {
          const {data} = notification;
          if (data!.type === 'ARTICLE') {
            return `${rootUrl}/site/news/${data!.id}`;
          }
          if (data!.type === 'TRANSFER') {
            return `${rootUrl}/site/player/${data!.id}`;
          }
        }

        return null;
      } catch (error) {
        return null;
      }
    },
  }}>
  <App />
</NotificationContainer>

在索引文件(App.tsx)中,我还注册了一个监听器,用于在应用程序已经启动但在后台打开通知时,使用onNotificationOpenedApp

onNotificationOpenedApp

useEffect(() => {
  const unsubscribeOnNotificationOpenedApp =
      messaging().onNotificationOpenedApp(remoteMessage => {
        if (!remoteMessage.data) return;
        const {type, id} = remoteMessage.data;
        if (!id) return;
        if (type === 'TRANSFER') {
          loadPlayer(Number(id));
        } else {
          loadArticle(Number(id));
        }
      });

  return unsubscribeOnNotificationOpenedApp;
}, [])

标签: reactjsreact-nativenavigationfirebase-cloud-messaging

解决方案


推荐阅读