我能够处理通知响应并通过链接和订阅触发导航,但这仅在应用程序处于前台或后台时才有效。如果应用程序被终止/关闭,则不会触发 subscribe 上的侦听器。我尝试将 addNotificationResponseReceivedListener 移动到 App.tsx,但是这样虽然我可以在两种情况下(前台、后台和终止/关闭)处理通知响应,但我无法使用深层链接进行导航,因为导航尚未准备好。 我的代码适用于背景和前景情况:
App.js
import {
useFonts,
Jost_400Regular,
Jost_600SemiBold,
} from '@expo-google-fonts/jost';
import AppLoading from 'expo-app-loading';
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import Routes from './src/routes';
import * as Notifications from 'expo-notifications';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
}),
});
export default function App() {
const [fontsLoaded] = useFonts({
Jost_400Regular,
Jost_600SemiBold,
});
return fontsLoaded ? (
<SafeAreaProvider>
<Routes />
</SafeAreaProvider>
) : (
<AppLoading />
);
}
路由/index.tsx
import {
NavigationContainer,
NavigationContainerRef,
} from '@react-navigation/native';
import React from 'react';
import { Linking } from 'react-native';
import StackRoutes from './stack.routes';
import * as Notifications from 'expo-notifications';
const navigationRef = React.createRef<NavigationContainerRef>();
const Routes: React.FC = () => {
return (
<NavigationContainer
ref={navigationRef}
linking={{
prefixes: ['plantmanager://'],
config: {
screens: {
TabBar: {
screens: {
MyPlants: 'myplants',
},
},
},
},
subscribe(listener) {
const onReceiveURL = ({ url }: { url: string }) => listener(url);
Linking.addEventListener('url', onReceiveURL);
const subscription = Notifications.addNotificationResponseReceivedListener(
(response) => {
const url = response.notification.request.content.data
.url as string;
console.log("Notification's url: ", url);
listener(url);
}
);
return () => {
Linking.removeEventListener('url', onReceiveURL);
subscription.remove();
};
},
}}
>
<StackRoutes />
</NavigationContainer>
);
};
export default Routes;
代码调度通知
await Notifications.scheduleNotificationAsync({
content: {
title: 'Heeeeey ?',
body: `It's time to take care of your ${plant.name}`,
sound: true,
priority: Notifications.AndroidNotificationPriority.HIGH,
data: {
plant,
url: 'plantmanager://myplants',
},
},
trigger: {
seconds: 10,
repeats: true,
},
});