0

我正在尝试使用已终止的应用程序访问推送通知数据。我一直在阅读文档并实施了提供的步骤,但我仍然没有得到任何数据,就像没有检测到推送通知一样。

我正在使用:“expo”:“^42.0.0”,“expo-notifications”:“~0.12.3”,

代码如下:

import { enableScreens } from 'react-native-screens'
import { NavigationContainer } from '@react-navigation/native';
import CarNavigator from './src/navigation/CarNavigator'
import { Alert } from 'react-native';
import React, { useState, useEffect, useRef } from 'react'
import * as Notifications from 'expo-notifications'
import Constants from 'expo-constants';

enableScreens();

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

export default function App() {

  const [expoPushToken, setExpoPushToken] = useState('');
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

  const registerForPushNotificationsAsync = async () => {
    let token;

    if (Constants.isDevice) {
      const { status: existingStatus } = await Notifications.getPermissionsAsync();
      let finalStatus = existingStatus;
      if (existingStatus !== 'granted') {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
      }
      if (finalStatus !== 'granted') {
        console.log('Failed to get push token for push notification!');
        return;
      }
      token = (await Notifications.getExpoPushTokenAsync()).data;
    } else {
      console.log('Must use physical device for Push Notifications');
    }

    if (Platform.OS === 'android') {
      Notifications.setNotificationChannelAsync('default', {
        name: 'default',
        importance: Notifications.AndroidImportance.MAX,
        vibrationPattern: [0, 250, 250, 250],
        lightColor: '#FF231F7C',
      });
    }

    return token;
  }

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

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

    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
      Alert.alert('IN');
    });

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

  return (
    <NavigationContainer>
      <CarNavigator />
    </NavigationContainer>
  )
}

根据文档,这部分在应用程序被杀死时处理推送通知数据,如下所述: https ://docs.expo.dev/versions/latest/sdk/notifications/#listening-to-notification-events

responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
      Alert.alert('IN');
    });

当我发送推送通知并使用该通知启动应用程序时,不会触发警报,就像未检测到推送通知一样。

我正在使用独立的 apk 构建在 android 上对此进行测试。

有人遇到过这个问题并设法解决了吗?

非常感谢,

4

0 回答 0