我在 React Native (expo) 中使用 expo-notifications 包来处理传入的通知。当应用程序位于后台和前台时,我可以正确收到通知 - 为了发送通知,我在后端使用“expo-server-sdk”包。我可以使用 expo-notification 包中的 addNotificationReceivedListener() 函数处理前台通知接收。用于处理 expo 文档中的后台通知接收(链接:- https://docs.expo.dev/versions/latest/sdk/notifications/#handling -incoming-notifications-when-the-app-is-1)他们说我们可以使用 expo-task-manager 库来处理它。下面给出了我参考博览会文档编写的代码。
...
import * as Notifications from 'expo-notifications';
import * as TaskManager from 'expo-task-manager';
...
//This code is written in root file and outside any react component
const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';
TaskManager.defineTask(
BACKGROUND_NOTIFICATION_TASK,
({ data, error, executionInfo }) =>{
if(error){
console.log('error occurred');
}
if(data){
console.log('data-----',data);
}
})
Run Code Online (Sandbox Code Playgroud)
//This code is written in App.js root component
useEffect(() => {
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
return()=>{
Notifications.unregisterTaskAsync(BACKGROUND_NOTIFICATION_TASK); …Run Code Online (Sandbox Code Playgroud)