当应用程序被杀死/关闭时,Expo 通知不会触发方法

时间:2021-03-09 13:54:36

标签: react-native push-notification expo

当应用程序正在运行或在后台但应用程序关闭时,我使用 react native expo 和推送通知工作正常。它不调用方法来处理通知。我需要重定向到详细信息页面。我尝试使用函数组件和类组件,尝试迁移到旧通知和新通知。

import React, {useState, useEffect, useRef} from 'react';
import {
    Image, ScrollView,
    StyleSheet, Text, TouchableOpacity, Platform,
    View, Linking,

} from 'react-native';
import * as Notifications from "expo-notifications";


const HomeScreen = (props) => {
  useEffect(() => {
        notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
        
            const {request, date} = notification ||{}
            const {content} = request ||{}
            const {data} = content ||{}
            const {annKey,type} = data ||{}
           
            if(annKey) {
              //  navigation.navigate('Detail', {annKey,  updateFeed: true, onSelect},)
            }
         

        });


        responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
           

            const {notification} = response ||{}
            console.log(notification);
            const {request, date} = notification ||{}
            const {content} = request ||{}
            const {data} = content ||{}
            const {annKey, type} = data ||{}


            if(annKey){
               navigation.navigate('Detail', {annKey,  updateFeed: true, onSelect},)
            }

          
        });

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

}

export default HomeScreen;

2 个答案:

答案 0 :(得分:0)

问题是在应用完成初始化后调用 expo-notifications 太晚了。因此,在系统放弃通知之前不会添加侦听器,也不会调用处理程序。

幸运的是,由于您使用的是新的 useLastNotificationResponse() 库,因此它引入了 addNotificationResponseReceivedListener() React 钩子。它可以替换 useEffect() 侦听器并返回用户与之交互的最后一个通知(即点击)。它可以安全地用于 import * as Notifications from 'expo-notifications'; export default function App() { const lastNotificationResponse = Notifications.useLastNotificationResponse(); React.useEffect(() => { if ( lastNotificationResponse && lastNotificationResponse.notification.request.content.data['someDataToCheck'] && lastNotificationResponse.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER ) { // navigate to your desired screen } }, [lastNotificationResponse]); return ( /* * your app */ ); } 钩子中。

您可以在此处找到文档:https://docs.expo.io/versions/latest/sdk/notifications/#uselastnotificationresponse-undefined--notificationresponse--null

这里是如何使用它(最好在你的根组件上实现它):

Scaffold

答案 1 :(得分:0)

您必须将此添加到您的 app.json 文件中:

    "android": {
      "useNextNotificationsApi": true,
    },