世博会本地通知在后台

时间:2020-11-12 19:18:50

标签: javascript react-native push-notification notifications expo

我正在将expo用于本机应用程序。我想添加一个功能,当实际时间与代码中的硬编码时间相同时,我可以显示通知。问题是,当我在博览会中打开我的应用程序时,它可以工作,但是当它在后台时,它却无法工作。 这是应该在后台运行的通知处理程序:

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

这是设置推送通知的useEffect:

useEffect(() => {
    registerForPushNotificationsAsync().then((token: any) => {
      setExpoPushToken(token);
    });

    notificationListener.current = Notifications.addNotificationReceivedListener(
      (notification: any) => {
        setNotification(notification);
      }
    );

    responseListener.current = Notifications.addNotificationResponseReceivedListener(
      (response) => {
        console.log(response);
      }
    );

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

这是用于注册和发送令牌通知的代码:

async function sendPushNotification() {
    await Notifications.scheduleNotificationAsync({
      content: {
        title: "You've got mail! ?",
        body: "Here is the notification body",
        data: { data: "goes here" },
      },
      trigger: { seconds: 1 },
    });
  }

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

    return token;
  }

所以我只使用sendPushNotification()函数发送它。当我打开应用程序时它可以工作,但是将其最小化后它什么也没显示。我该如何解决?

0 个答案:

没有答案