打开通知后导航到屏幕? [英] Navigate to screen after opening a notification?

查看:28
本文介绍了打开通知后导航到屏幕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Firebase 云功能向我收到他的 FCM 令牌的特定设备发送远程通知,我收到了它并且运行良好,

I'm using Firebase cloud functions to send a remote notification to a specific device I got his FCM Token, and I receive it and works very well,

这是我通过云函数发送通知的代码

Here is my code to send a notification by Cloud functions

const functions = require("firebase-functions");
const admin = require("firebase-admin");
var serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://-----.firebaseio.com"
});
exports.sendPushR = functions.database
  .ref("/request/{pid}/orders/{orderid}")
  .onCreate(async (snapshot, context) => {
    const registrationTokens = snapshot.val().token;
    const event = context.params;
    const afterData = snapshot.val();
    const username = snapshot.val().username;

    const payload = {
      notification: {
        title: "New Order",
        body: `You received a new order from ${username} check it now! `,
        sound: "default",
        icon: "default"
      }
    };

    try {
      const response = await admin
        .messaging()
        .sendToDevice(registrationTokens, payload);
      console.log("Successfully sent message:", response);
    } catch (error) {
      console.log("Error sending message:", error);
    }
    return null;
  });

在主屏幕应用程序中

  async componentDidMount() {
//BackHandler.addEventListener("hardwareBackPress", this.backPressed);

this.notificationInitListener = await firebase
  .notifications()
  .getInitialNotification()
  .then(notificationOpen => {
    if (notificationOpen) {
      console.log(notificationOpen);
      setTimeout(() => {
        this.props.navigation.navigate("Notifications");
      }, 5000);
      console.log("1---OPEND");
      firebase.notifications().removeAllDeliveredNotifications();
      console.log("1---OPEND-After");
    }
  });
this.removeNotificationOpenedListener = firebase
  .notifications()
  .onNotificationOpened(notificationOpen => {
    // Get the action triggered by the notification being opened
    // const action = notificationOpen.action;
    // Get information about the notification that was opened
    // const notification = notificationOpen.notification;
    if (notificationOpen) {
      this.props.navigation.navigate("Notifications");
      console.log("OPEND");
      firebase.notifications().removeAllDeliveredNotifications();
      console.log("OPEND-After");
    }
  });
 }

路线

const HomeStack = createStackNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: ({ navigation }) => ({
        title: "Home",
        headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
        headerRight: (
          <TouchableOpacity
            onPress={() => navigation.navigate("Notifications")}
            style={{ margin: 10 }}
          >
            <Icon name="ios-notifications" size={28} color="#1DA1F2" />
          </TouchableOpacity>
        )
      })
    },
    MapScreen: {
      screen: MapScreen,
      navigationOptions: {
        title: "Map"
      }
    },
    ProviderProfile: {
      screen: ProviderProfile
    },
    GalleryDetails: {
      screen: GalleryDetails,
      navigationOptions: {
        title: "Gallery Details"
      }
    },
    Order: {
      screen: Order,
      navigationOptions: {
        title: "Order"
      }
    },

    Favorites: {
      screen: UserFavorites,
      navigationOptions: ({ navigation }) => ({
        title: "My Favorites!",
        headerLeft: <NavigationDrawerStructure navigationProps={navigation} />
      })
    },
    Notifications: {
      screen: Notifications,
      navigationOptions: {
        title: "Notifications"
      }
    }
  },
  {
    defaultNavigationOptions
  }
);

现在我有两个问题:

  1. 我认为这是在第一个函数 getInitialNotification 中,这是我第一次打开应用程序时没有点击任何通知,它会将我导航到通知屏幕两三秒钟,然后让我回到家,和
  2. 当我点击收到的通知时,当应用程序关闭时'它不在后台'正在杀死'"!,只是停留在主屏幕,无法导航到通知屏幕或导航我我想 2 秒钟,然后让我回到主屏幕,
  1. I think that's in the first function getInitialNotification that's at the first time I open the app without clicking on any notification it navigates me to Notifications Screen for a two or three second and get me back to the home, and
  2. when I click the notification I received "when app is closing 'it's not in background 'Killing' "!, just stuck in the Home screen not navigate me to notifications screen OR Navigate me I think for 2 seconds and get me back to Home Screen,

但是当应用程序仍在后台时,底层函数onNotificationOpened"运行良好

But the under function "onNotificationOpened" works very well when the app is still in the background

演示https://vimeo.com/350006721

推荐答案

在通知打开时处理导航的最佳方式是在初始屏幕中处理它们.这会给你更多的灵活性.只需检查应用程序是否通过通知打开,在 componentDidMount 中,然后导航到所需的屏幕.您可以使用 createSwitchNavigator 来防止 android 后退按钮和 ios 手势返回初始屏幕.

Best way to handle navigation on notification opening is to handle them in a splash screen. this will give you more flexibility. just check if the app is opened by notification, in componentDidMount, And navigate to the desired screen. you can use createSwitchNavigator to prevent android back button and ios gesture, from going back to the splash screen.

我认为当我收到应用程序被杀"通知时的第二个问题是然后点击打开它,它打开得很好,导航到通知屏幕";但是每次在我打开应用程序而不点击任何通知后,它都会将我导航到通知屏幕",所以我如何删除之前的通知删除 getInitialNotification 中的侦听器"

I think the second issue when I receive a notification "when app killed" and click to open it, it's opened very well and navigate me to "Notifications Screen" But in every time after I open the app without click to any notification it navigates me to "Notifications Screen", SO How can I remove the previous notification "remove the listener in getInitialNotification "

要解决此问题,您必须在处理通知之后和导航到新屏幕之前将 messageId/notificationId 保存在 AsyncStorage 中.在处理通知之前,您可以检查该通知是否已处理.

To solve this issue you have to save the messageId/notificationId in AsyncStorage after processing the notification and before navigating to the new screen. And just before processing the notification you can check if that notification is already processed.

您必须采取的步骤:

1- 检查之前是否处理过 notificationId(这可以是 AsyncStorage 调用).

1- check if the notificationId is processed before ( this can be an AsyncStorage call).

2- 如果已处理:清除 AsyncStorage,因为我们不再需要它

2- if processed: clear AsyncStorage, 'cause we don't need it anymore

3- 如果不是:将 notificationId 添加到 AsyncStorage 并导航到新屏幕

3- if not: add the notificationId to AsyncStorage and navigate to the new screen

这篇关于打开通知后导航到屏幕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆