打开通知后导航到屏幕吗?

时间:2019-07-23 20:32:51

标签: javascript android reactjs firebase react-native

我正在使用Firebase云功能将远程通知发送到特定设备,我获得了他的FCM令牌,并且我收到了它,并且效果很好,

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

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秒钟,然后回到主屏幕,

但是当应用程序仍在后台时,“ onNotificationOpened ”功能会非常好

演示 https://vimeo.com/350006721

2 个答案:

答案 0 :(得分:0)

您没有解释您的期望。.但是我想您不想从该通知屏幕开始,而是从主屏幕开始。

为此,您可以将initialRouteName用作createStackNavigator方法的第二个参数(请参见本页最底部的示例:https://reactnavigation.org/docs/en/stack-navigator.html

尝试一下,如果解决了,那就去寻找第二个问题(我更喜欢逐步解决问题)

答案 1 :(得分:0)

在打开通知时处理导航的最佳方法是在启动屏幕中处理它们。这将为您提供更大的灵活性。只需检查componentDidMount中是否已通过通知打开应用程序,然后导航至所需的屏幕。您可以使用cresateSwitchNavigator来防止android后退按钮和ios手势回到初始屏幕。

  

我认为第二个问题是,当我收到“应用程序被杀死”并单击以打开通知时,它的打开效果非常好,并导航至“通知屏幕”,但是每次我打开应用程序后都没有单击任何通知它会将我导航到“通知屏幕”,因此,如何删除先前的通知“删除getInitialNotification中的侦听器”

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

您必须采取的步骤:

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

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

3-如果没有,则:将notificationId添加到AsyncStorage并导航到新屏幕